CMS 3D CMS Logo

MkFinder.cc
Go to the documentation of this file.
1 #include "MkFinder.h"
2 
5 #include "CandCloner.h"
6 #include "FindingFoos.h"
7 #include "KalmanUtilsMPlex.h"
8 #include "MatriplexPackers.h"
9 #include "MiniPropagators.h"
10 
11 //#define DEBUG
12 #include "Debug.h"
13 
14 #if defined(MKFIT_STANDALONE)
16 #endif
17 
18 #ifdef RNT_DUMP_MkF_SelHitIdcs
19 // declares struct RntIfc_selectHitIndices rnt_shi in unnamed namespace;
20 #include "RecoTracker/MkFitCore/standalone/RntDumper/MkFinder_selectHitIndices.icc"
21 #endif
22 
23 #include "vdt/atan2.h"
24 
25 #include <algorithm>
26 #include <queue>
27 
28 namespace mkfit {
29 
31  const IterationConfig &ic,
32  const IterationParams &ip,
33  const IterationLayerConfig &ilc,
34  const SteeringParams &sp,
35  const std::vector<bool> *ihm,
36  const Event *ev,
37  int region,
38  bool infwd) {
39  m_prop_config = &pc;
40  m_iteration_config = &ic;
41  m_iteration_params = &ip;
43  m_steering_params = &sp;
45  m_event = ev;
47  m_in_fwd = infwd;
48  }
49 
50  void MkFinder::setup_bkfit(const PropagationConfig &pc, const SteeringParams &sp, const Event *ev) {
51  m_prop_config = &pc;
52  m_steering_params = &sp;
53  m_event = ev;
54  }
55 
57  m_prop_config = nullptr;
58  m_iteration_config = nullptr;
59  m_iteration_params = nullptr;
60  m_iteration_layer_config = nullptr;
61  m_steering_params = nullptr;
62  m_iteration_hit_mask = nullptr;
63  m_event = nullptr;
64  m_current_region = -1;
65  m_in_fwd = true;
66  }
67 
68  void MkFinder::begin_layer(const LayerOfHits &layer_of_hits) {
69 #ifdef RNT_DUMP_MkF_SelHitIdcs
70  const LayerOfHits &L = layer_of_hits;
71  const LayerInfo &LI = *L.layer_info();
72  rnt_shi.ResetH();
73  rnt_shi.ResetF();
74  *rnt_shi.h = {m_event->evtID(),
78  L.layer_id(),
79  L.is_barrel() ? LI.rin() : LI.zmin(),
80  LI.is_barrel() ? LI.rout() : LI.zmax(),
81  L.is_barrel(),
82  L.is_pixel(),
83  L.is_stereo()};
84  *rnt_shi.f = *rnt_shi.h;
85 #endif
86  }
87 
89 #ifdef RNT_DUMP_MkF_SelHitIdcs
90  rnt_shi.FillH();
91  rnt_shi.FillF();
92 #endif
93  }
94 
95  //==============================================================================
96  // Input / Output TracksAndHitIdx
97  //==============================================================================
98 
99  void MkFinder::inputTracksAndHitIdx(const std::vector<Track> &tracks, int beg, int end, bool inputProp) {
100  // Assign track parameters to initial state and copy hit values in.
101 
102  // This might not be true for the last chunk!
103  // assert(end - beg == NN);
104 
105  const int iI = inputProp ? iP : iC;
106 
107  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
108  copy_in(tracks[i], imp, iI);
109  }
110  }
111 
113  const std::vector<Track> &tracks, const std::vector<int> &idxs, int beg, int end, bool inputProp, int mp_offset) {
114  // Assign track parameters to initial state and copy hit values in.
115 
116  // This might not be true for the last chunk!
117  // assert(end - beg == NN);
118 
119  const int iI = inputProp ? iP : iC;
120 
121  for (int i = beg, imp = mp_offset; i < end; ++i, ++imp) {
122  copy_in(tracks[idxs[i]], imp, iI);
123  }
124  }
125 
126  void MkFinder::inputTracksAndHitIdx(const std::vector<CombCandidate> &tracks,
127  const std::vector<std::pair<int, int>> &idxs,
128  int beg,
129  int end,
130  bool inputProp) {
131  // Assign track parameters to initial state and copy hit values in.
132 
133  // This might not be true for the last chunk!
134  // assert(end - beg == NN);
135 
136  const int iI = inputProp ? iP : iC;
137 
138  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
139  const TrackCand &trk = tracks[idxs[i].first][idxs[i].second];
140 
141  copy_in(trk, imp, iI);
142 
143  m_SeedIdx(imp, 0, 0) = idxs[i].first;
144  m_CandIdx(imp, 0, 0) = idxs[i].second;
145  m_SeedOriginIdx[imp] = tracks[idxs[i].first].seed_origin_index();
146  }
147  }
148 
149  void MkFinder::inputTracksAndHits(const std::vector<CombCandidate> &tracks,
150  const LayerOfHits &layer_of_hits,
151  const std::vector<UpdateIndices> &idxs,
152  int beg,
153  int end,
154  bool inputProp) {
155  // Assign track parameters to initial state and copy hit values in.
156 
157  // This might not be true for the last chunk!
158  // assert(end - beg == NN);
159 
160  const int iI = inputProp ? iP : iC;
161 
162  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
163  const TrackCand &trk = tracks[idxs[i].seed_idx][idxs[i].cand_idx];
164 
165  copy_in(trk, imp, iI);
166 
167  m_SeedIdx(imp, 0, 0) = idxs[i].seed_idx;
168  m_CandIdx(imp, 0, 0) = idxs[i].cand_idx;
169  m_SeedOriginIdx[imp] = tracks[idxs[i].seed_idx].seed_origin_index();
170 
171  // Reuse selectHitIndices() arrays -- used also in packModuleNormDir()
172  m_XHitArr(imp, 0, 0) = idxs[i].hit_idx;
173  m_XHitSize(imp, 0, 0) = 1;
174 
175  const Hit &hit = layer_of_hits.refHit(idxs[i].hit_idx);
176  m_msErr.copyIn(imp, hit.errArray());
177  m_msPar.copyIn(imp, hit.posArray());
178  }
179  }
180 
181  void MkFinder::inputOverlapHits(const LayerOfHits &layer_of_hits,
182  const std::vector<UpdateIndices> &idxs,
183  int beg,
184  int end) {
185  // Copy overlap hit values in.
186 
187  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
188  const Hit &hit = layer_of_hits.refHit(idxs[i].ovlp_idx);
189  m_msErr.copyIn(imp, hit.errArray());
190  m_msPar.copyIn(imp, hit.posArray());
191  }
192  }
193 
194  void MkFinder::inputTracksAndHitIdx(const std::vector<CombCandidate> &tracks,
195  const std::vector<std::pair<int, IdxChi2List>> &idxs,
196  int beg,
197  int end,
198  bool inputProp) {
199  // Assign track parameters to initial state and copy hit values in.
200 
201  // This might not be true for the last chunk!
202  // assert(end - beg == NN);
203 
204  const int iI = inputProp ? iP : iC;
205 
206  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
207  const TrackCand &trk = tracks[idxs[i].first][idxs[i].second.trkIdx];
208 
209  copy_in(trk, imp, iI);
210 
211  m_SeedIdx(imp, 0, 0) = idxs[i].first;
212  m_CandIdx(imp, 0, 0) = idxs[i].second.trkIdx;
213  m_SeedOriginIdx[imp] = tracks[idxs[i].first].seed_origin_index();
214  }
215  }
216 
217  void MkFinder::outputTracksAndHitIdx(std::vector<Track> &tracks, int beg, int end, bool outputProp) const {
218  // Copies requested track parameters into Track objects.
219  // The tracks vector should be resized to allow direct copying.
220 
221  const int iO = outputProp ? iP : iC;
222 
223  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
224  copy_out(tracks[i], imp, iO);
225  }
226  }
227 
229  std::vector<Track> &tracks, const std::vector<int> &idxs, int beg, int end, bool outputProp) const {
230  // Copies requested track parameters into Track objects.
231  // The tracks vector should be resized to allow direct copying.
232 
233  const int iO = outputProp ? iP : iC;
234 
235  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
236  copy_out(tracks[idxs[i]], imp, iO);
237  }
238  }
239 
241  const LayerOfHits &layer_of_hits, int hit_cnt, MPlexHV &norm, MPlexHV &dir, int N_proc) const {
242  for (int itrack = 0; itrack < N_proc; ++itrack) {
243  if (hit_cnt < m_XHitSize[itrack]) {
244  const auto &hit = layer_of_hits.refHit(m_XHitArr.constAt(itrack, hit_cnt, 0));
245  unsigned int mid = hit.detIDinLayer();
246  const ModuleInfo &mi = layer_of_hits.layer_info()->module_info(mid);
247  norm.At(itrack, 0, 0) = mi.zdir[0];
248  norm.At(itrack, 1, 0) = mi.zdir[1];
249  norm.At(itrack, 2, 0) = mi.zdir[2];
250  dir.At(itrack, 0, 0) = mi.xdir[0];
251  dir.At(itrack, 1, 0) = mi.xdir[1];
252  dir.At(itrack, 2, 0) = mi.xdir[2];
253  }
254  }
255  }
256 
257  //==============================================================================
258  // getHitSelDynamicWindows
259  //==============================================================================
260  // From HitSelectionWindows.h: track-related config on hit selection windows
261 
263  const float invpt, const float theta, float &min_dq, float &max_dq, float &min_dphi, float &max_dphi) {
264  float max_invpt = std::min(invpt, 10.0f); // => pT>0.1 GeV
265 
266  enum SelWinParameters_e { dp_sf = 0, dp_0, dp_1, dp_2, dq_sf, dq_0, dq_1, dq_2 };
268 
269  if (!v.empty()) {
270  // dq hit selection window
271  float this_dq = v[dq_sf] * (v[dq_0] * max_invpt + v[dq_1] * theta + v[dq_2]);
272  // In case value is below 0 (bad window derivation or other reasons), leave original limits
273  if (this_dq > 0.f) {
274  min_dq = this_dq;
275  max_dq = 2.0f * min_dq;
276  }
277 
278  // dphi hit selection window
279  float this_dphi = v[dp_sf] * (v[dp_0] * max_invpt + v[dp_1] * theta + v[dp_2]);
280  // In case value is too low (bad window derivation or other reasons), leave original limits
281  if (this_dphi > min_dphi) {
282  min_dphi = this_dphi;
283  max_dphi = 2.0f * min_dphi;
284  }
285  }
286  }
287 
288  //==============================================================================
289  // getHitSelDynamicChi2Cut
290  //==============================================================================
291  // From HitSelectionWindows.h: track-related config on hit selection windows
292 
293  inline float MkFinder::getHitSelDynamicChi2Cut(const int itrk, const int ipar) {
294  const float minChi2Cut = m_iteration_params->chi2Cut_min;
295  const float invpt = m_Par[ipar].At(itrk, 3, 0);
296  const float theta = std::abs(m_Par[ipar].At(itrk, 5, 0) - Const::PIOver2);
297 
298  float max_invpt = std::min(invpt, 10.0f); // => pT>0.1 GeV
299 
300  enum SelWinParameters_e { c2_sf = 8, c2_0, c2_1, c2_2 };
302 
303  if (!v.empty()) {
304  float this_c2 = v[c2_sf] * (v[c2_0] * max_invpt + v[c2_1] * theta + v[c2_2]);
305  // In case value is too low (bad window derivation or other reasons), leave original limits
306  if (this_c2 > minChi2Cut)
307  return this_c2;
308  }
309  return minChi2Cut;
310  }
311 
312  //==============================================================================
313  // SelectHitIndices
314  //==============================================================================
315 
316  void MkFinder::selectHitIndices(const LayerOfHits &layer_of_hits, const int N_proc, bool fill_binsearch_only) {
317  // bool debug = true;
318  using bidx_t = LayerOfHits::bin_index_t;
319  using bcnt_t = LayerOfHits::bin_content_t;
320  const LayerOfHits &L = layer_of_hits;
322 
323  const int iI = iP;
324  const float nSigmaPhi = 3;
325  const float nSigmaZ = 3;
326  const float nSigmaR = 3;
327 
328  dprintf("LayerOfHits::SelectHitIndices %s layer=%d N_proc=%d\n",
329  L.is_barrel() ? "barrel" : "endcap",
330  L.layer_id(),
331  N_proc);
332 
333  float dqv[NN], dphiv[NN], qv[NN], phiv[NN];
334  bidx_t qb1v[NN], qb2v[NN], qbv[NN], pb1v[NN], pb2v[NN];
335 
336  const auto assignbins = [&](int itrack,
337  float q,
338  float dq,
339  float phi,
340  float dphi,
341  float min_dq,
342  float max_dq,
343  float min_dphi,
344  float max_dphi) {
345  dphi = std::clamp(std::abs(dphi), min_dphi, max_dphi);
346  dq = std::clamp(dq, min_dq, max_dq);
347  //
348  qv[itrack] = q;
349  phiv[itrack] = phi;
350  dphiv[itrack] = dphi;
351  dqv[itrack] = dq;
352  //
353  qbv[itrack] = L.qBinChecked(q);
354  qb1v[itrack] = L.qBinChecked(q - dq);
355  qb2v[itrack] = L.qBinChecked(q + dq) + 1;
356  pb1v[itrack] = L.phiBinChecked(phi - dphi);
357  pb2v[itrack] = L.phiMaskApply(L.phiBin(phi + dphi) + 1);
358  };
359 
360  const auto calcdphi2 = [&](int itrack, float dphidx, float dphidy) {
361  return dphidx * dphidx * m_Err[iI].constAt(itrack, 0, 0) + dphidy * dphidy * m_Err[iI].constAt(itrack, 1, 1) +
362  2 * dphidx * dphidy * m_Err[iI].constAt(itrack, 0, 1);
363  };
364 
365  const auto calcdphi = [&](float dphi2, float min_dphi) {
366  return std::max(nSigmaPhi * std::sqrt(std::abs(dphi2)), min_dphi);
367  };
368 
369  if (L.is_barrel()) {
370  // Pull out the part of the loop that vectorizes with icc and gcc
371  // In llvm16 clang issues a warning that it can't vectorize
372  // the loop. Unfortunately, there doesn't seem to be a
373  // pragma to suppress the warning, so we ifdef it out. This
374  // should be rechecked if llvm vectorization improves.
375 #if !defined(__clang__)
376 #pragma omp simd
377 #endif
378  for (int itrack = 0; itrack < NN; ++itrack) {
379  m_XHitSize[itrack] = 0;
380 
381  float min_dq = ILC.min_dq();
382  float max_dq = ILC.max_dq();
383  float min_dphi = ILC.min_dphi();
384  float max_dphi = ILC.max_dphi();
385 
386  const float invpt = m_Par[iI].At(itrack, 3, 0);
387  const float theta = std::fabs(m_Par[iI].At(itrack, 5, 0) - Const::PIOver2);
388  getHitSelDynamicWindows(invpt, theta, min_dq, max_dq, min_dphi, max_dphi);
389 
390  const float x = m_Par[iI].constAt(itrack, 0, 0);
391  const float y = m_Par[iI].constAt(itrack, 1, 0);
392  const float r2 = x * x + y * y;
393  const float dphidx = -y / r2, dphidy = x / r2;
394  const float dphi2 = calcdphi2(itrack, dphidx, dphidy);
395 #ifdef HARD_CHECK
396  assert(dphi2 >= 0);
397 #endif
398 
399  const float phi = getPhi(x, y);
400  float dphi = calcdphi(dphi2, min_dphi);
401 
402  const float z = m_Par[iI].constAt(itrack, 2, 0);
403  const float dz = std::abs(nSigmaZ * std::sqrt(m_Err[iI].constAt(itrack, 2, 2)));
404  const float edgeCorr = std::abs(0.5f * (L.layer_info()->rout() - L.layer_info()->rin()) /
405  std::tan(m_Par[iI].constAt(itrack, 5, 0)));
406  // XXX-NUM-ERR above, m_Err(2,2) gets negative!
407 
408  m_XWsrResult[itrack] = L.is_within_z_sensitive_region(z, std::sqrt(dz * dz + edgeCorr * edgeCorr));
409  assignbins(itrack, z, dz, phi, dphi, min_dq, max_dq, min_dphi, max_dphi);
410 
411  // Relax propagation-fail detection to be in line with pre-43145.
412  if (m_FailFlag[itrack] && std::sqrt(r2) >= L.layer_info()->rin()) {
413  m_FailFlag[itrack] = 0;
414  }
415  }
416  } else // endcap
417  {
418  //layer half-thikness for dphi spread calculation; only for very restrictive iters
419  const float layerD = std::abs(L.layer_info()->zmax() - L.layer_info()->zmin()) * 0.5f *
421  // Pull out the part of the loop that vectorizes with icc and gcc
422 #if !defined(__clang__)
423 #pragma omp simd
424 #endif
425  for (int itrack = 0; itrack < NN; ++itrack) {
426  m_XHitSize[itrack] = 0;
427 
428  float min_dq = ILC.min_dq();
429  float max_dq = ILC.max_dq();
430  float min_dphi = ILC.min_dphi();
431  float max_dphi = ILC.max_dphi();
432 
433  const float invpt = m_Par[iI].At(itrack, 3, 0);
434  const float theta = std::fabs(m_Par[iI].At(itrack, 5, 0) - Const::PIOver2);
435  getHitSelDynamicWindows(invpt, theta, min_dq, max_dq, min_dphi, max_dphi);
436 
437  const float x = m_Par[iI].constAt(itrack, 0, 0);
438  const float y = m_Par[iI].constAt(itrack, 1, 0);
439  const float r2 = x * x + y * y;
440  const float r2Inv = 1.f / r2;
441  const float dphidx = -y * r2Inv, dphidy = x * r2Inv;
442  const float phi = getPhi(x, y);
443  const float dphi2 =
444  calcdphi2(itrack, dphidx, dphidy)
445  //range from finite layer thickness
446  + std::pow(layerD * std::tan(m_Par[iI].At(itrack, 5, 0)) * std::sin(m_Par[iI].At(itrack, 4, 0) - phi), 2) *
447  r2Inv;
448 #ifdef HARD_CHECK
449  assert(dphi2 >= 0);
450 #endif
451 
452  float dphi = calcdphi(dphi2, min_dphi);
453 
454  const float r = std::sqrt(r2);
455  const float dr = nSigmaR * std::sqrt(std::abs(x * x * m_Err[iI].constAt(itrack, 0, 0) +
456  y * y * m_Err[iI].constAt(itrack, 1, 1) +
457  2 * x * y * m_Err[iI].constAt(itrack, 0, 1)) /
458  r2);
459  const float edgeCorr = std::abs(0.5f * (L.layer_info()->zmax() - L.layer_info()->zmin()) *
460  std::tan(m_Par[iI].constAt(itrack, 5, 0)));
461 
462  m_XWsrResult[itrack] = L.is_within_r_sensitive_region(r, std::sqrt(dr * dr + edgeCorr * edgeCorr));
463  assignbins(itrack, r, dr, phi, dphi, min_dq, max_dq, min_dphi, max_dphi);
464  }
465  }
466 
467 #ifdef RNT_DUMP_MkF_SelHitIdcs
468  if (fill_binsearch_only) {
469  // XXX loop over good indices (prepared in V2) and put in V1 BinSearch results
470  for (auto i : rnt_shi.f_h_idcs) {
471  CandInfo &ci = (*rnt_shi.ci)[rnt_shi.f_h_remap[i]];
472  ci.bso = BinSearch({phiv[i],
473  dphiv[i],
474  qv[i],
475  dqv[i],
476  pb1v[i],
477  pb2v[i],
478  qb1v[i],
479  qb2v[i],
482  false});
483  }
484  return;
485  }
486 #endif
487 
488  // Vectorizing this makes it run slower!
489  //#pragma omp simd
490  for (int itrack = 0; itrack < N_proc; ++itrack) {
491  // PROP-FAIL-ENABLE The following to be enabled when propagation failure
492  // detection is properly implemented in propagate-to-R/Z.
493  if (m_FailFlag[itrack]) {
494  m_XWsrResult[itrack].m_wsr = WSR_Failed;
495  continue;
496  }
497 
498  if (m_XWsrResult[itrack].m_wsr == WSR_Outside) {
499  continue;
500  }
501 
502  const bidx_t qb = qbv[itrack];
503  const bidx_t qb1 = qb1v[itrack];
504  const bidx_t qb2 = qb2v[itrack];
505  const bidx_t pb1 = pb1v[itrack];
506  const bidx_t pb2 = pb2v[itrack];
507 
508  const float q = qv[itrack];
509  const float phi = phiv[itrack];
510  const float dphi = dphiv[itrack];
511  const float dq = dqv[itrack];
512 
513  // clang-format off
514  dprintf(" %2d/%2d: %6.3f %6.3f %6.6f %7.5f %3u %3u %4u %4u\n",
515  L.layer_id(), itrack, q, phi, dq, dphi,
516  qb1, qb2, pb1, pb2);
517  // clang-format on
518 
519 #if defined(DUMPHITWINDOW) && defined(MKFIT_STANDALONE)
520  const auto ngr = [](float f) { return isFinite(f) ? f : -999.0f; };
521 
522  const int seed_lbl = m_event->currentSeed(m_SeedOriginIdx[itrack]).label();
524  const int seed_mcid = (slfh.is_set() && slfh.good_frac() > 0.7f) ? slfh.label : -999999;
525 #endif
526 
527  for (bidx_t qi = qb1; qi != qb2; ++qi) {
528  for (bidx_t pi = pb1; pi != pb2; pi = L.phiMaskApply(pi + 1)) {
529  // Limit to central Q-bin
530  if (qi == qb && L.isBinDead(pi, qi) == true) {
531  dprint("dead module for track in layer=" << L.layer_id() << " qb=" << qi << " pi=" << pi << " q=" << q
532  << " phi=" << phi);
533  m_XWsrResult[itrack].m_in_gap = true;
534  }
535 
536  // MT: The following line is the biggest hog (4% total run time).
537  // This comes from cache misses, I presume.
538  // It might make sense to make first loop to extract bin indices
539  // and issue prefetches at the same time.
540  // Then enter vectorized loop to actually collect the hits in proper order.
541 
542  //SK: ~20x1024 bin sizes give mostly 1 hit per bin. Commented out for 128 bins or less
543  // #pragma nounroll
544  auto pbi = L.phiQBinContent(pi, qi);
545  for (bcnt_t hi = pbi.begin(); hi < pbi.end(); ++hi) {
546  // MT: Access into m_hit_zs and m_hit_phis is 1% run-time each.
547 
548  const unsigned int hi_orig = L.getOriginalHitIndex(hi);
549 
550  if (m_iteration_hit_mask && (*m_iteration_hit_mask)[hi_orig]) {
551  dprintf(
552  "Yay, denying masked hit on layer %u, hi %u, orig idx %u\n", L.layer_info()->layer_id(), hi, hi_orig);
553  continue;
554  }
555 
556  if (Config::usePhiQArrays) {
557  if (m_XHitSize[itrack] >= MPlexHitIdxMax)
558  break;
559 
560  const float ddq = std::abs(q - L.hit_q(hi));
561  const float ddphi = cdist(std::abs(phi - L.hit_phi(hi)));
562 
563  // clang-format off
564  dprintf(" SHI %3u %4u %5u %6.3f %6.3f %6.4f %7.5f %s\n",
565  qi, pi, hi, L.hit_q(hi), L.hit_phi(hi),
566  ddq, ddphi, (ddq < dq && ddphi < dphi) ? "PASS" : "FAIL");
567  // clang-format on
568 
569 #if defined(DUMPHITWINDOW) && defined(MKFIT_STANDALONE)
570  // clang-format off
571  MPlexQF thisOutChi2;
572  {
573  const MCHitInfo &mchinfo = m_event->simHitsInfo_[L.refHit(hi).mcHitID()];
574  int mchid = mchinfo.mcTrackID();
575  int st_isfindable = 0;
576  int st_label = -999999;
577  int st_prodtype = 0;
578  int st_nhits = -1;
579  int st_charge = 0;
580  float st_r = -999.;
581  float st_z = -999.;
582  float st_pt = -999.;
583  float st_eta = -999.;
584  float st_phi = -999.;
585  if (mchid >= 0) {
586  Track simtrack = m_event->simTracks_[mchid];
587  st_isfindable = (int)simtrack.isFindable();
588  st_label = simtrack.label();
589  st_prodtype = (int)simtrack.prodType();
590  st_pt = simtrack.pT();
591  st_eta = simtrack.momEta();
592  st_phi = simtrack.momPhi();
593  st_nhits = simtrack.nTotalHits();
594  st_charge = simtrack.charge();
595  st_r = simtrack.posR();
596  st_z = simtrack.z();
597  }
598 
599  const Hit &thishit = L.refHit(hi_orig);
600  m_msErr.copyIn(itrack, thishit.errArray());
601  m_msPar.copyIn(itrack, thishit.posArray());
602 
603  MPlexQI propFail;
604  MPlexLV tmpPropPar;
605  const FindingFoos &fnd_foos = FindingFoos::get_finding_foos(L.is_barrel());
606  (*fnd_foos.m_compute_chi2_foo)(m_Err[iI],
607  m_Par[iI],
608  m_Chg,
609  m_msErr,
610  m_msPar,
611  thisOutChi2,
612  tmpPropPar,
613  propFail,
614  N_proc,
617 
618  float hx = thishit.x();
619  float hy = thishit.y();
620  float hz = thishit.z();
621  float hr = std::hypot(hx, hy);
622  float hphi = std::atan2(hy, hx);
623  float hex = ngr( std::sqrt(thishit.exx()) );
624  float hey = ngr( std::sqrt(thishit.eyy()) );
625  float hez = ngr( std::sqrt(thishit.ezz()) );
626  float her = ngr( std::sqrt(
627  (hx * hx * thishit.exx() + hy * hy * thishit.eyy() + 2.0f * hx * hy * m_msErr.At(itrack, 0, 1)) /
628  (hr * hr)) );
629  float hephi = ngr( std::sqrt(thishit.ephi()) );
630  float hchi2 = ngr( thisOutChi2[itrack] );
631  float tx = m_Par[iI].At(itrack, 0, 0);
632  float ty = m_Par[iI].At(itrack, 1, 0);
633  float tz = m_Par[iI].At(itrack, 2, 0);
634  float tr = std::hypot(tx, ty);
635  float tphi = std::atan2(ty, tx);
636  // float tchi2 = ngr( m_Chi2(itrack, 0, 0) ); // unused
637  float tex = ngr( std::sqrt(m_Err[iI].At(itrack, 0, 0)) );
638  float tey = ngr( std::sqrt(m_Err[iI].At(itrack, 1, 1)) );
639  float tez = ngr( std::sqrt(m_Err[iI].At(itrack, 2, 2)) );
640  float ter = ngr( std::sqrt(
641  (tx * tx * tex * tex + ty * ty * tey * tey + 2.0f * tx * ty * m_Err[iI].At(itrack, 0, 1)) /
642  (tr * tr)) );
643  float tephi = ngr( std::sqrt(
644  (ty * ty * tex * tex + tx * tx * tey * tey - 2.0f * tx * ty * m_Err[iI].At(itrack, 0, 1)) /
645  (tr * tr * tr * tr)) );
646  float ht_dxy = std::hypot(hx - tx, hy - ty);
647  float ht_dz = hz - tz;
648  float ht_dphi = cdist(std::abs(hphi - tphi));
649 
650  static bool first = true;
651  if (first) {
652  printf(
653  "HITWINDOWSEL "
654  "evt_id/I:track_algo/I:"
655  "lyr_id/I:lyr_isbrl/I:hit_idx/I:"
656  "trk_cnt/I:trk_idx/I:trk_label/I:"
657  "trk_pt/F:trk_eta/F:trk_mphi/F:trk_chi2/F:"
658  "nhits/I:"
659  "seed_idx/I:seed_label/I:seed_mcid/I:"
660  "hit_mcid/I:"
661  "st_isfindable/I:st_prodtype/I:st_label/I:"
662  "st_pt/F:st_eta/F:st_phi/F:"
663  "st_nhits/I:st_charge/I:st_r/F:st_z/F:"
664  "trk_q/F:hit_q/F:dq_trkhit/F:dq_cut/F:trk_phi/F:hit_phi/F:dphi_trkhit/F:dphi_cut/F:"
665  "t_x/F:t_y/F:t_r/F:t_phi/F:t_z/F:"
666  "t_ex/F:t_ey/F:t_er/F:t_ephi/F:t_ez/F:"
667  "h_x/F:h_y/F:h_r/F:h_phi/F:h_z/F:"
668  "h_ex/F:h_ey/F:h_er/F:h_ephi/F:h_ez/F:"
669  "ht_dxy/F:ht_dz/F:ht_dphi/F:"
670  "h_chi2/F"
671  "\n");
672  first = false;
673  }
674 
675  if (!(std::isnan(phi)) && !(std::isnan(getEta(m_Par[iI].At(itrack, 5, 0))))) {
676  //|| std::isnan(ter) || std::isnan(her) || std::isnan(m_Chi2(itrack, 0, 0)) || std::isnan(hchi2)))
677  printf("HITWINDOWSEL "
678  "%d %d"
679  "%d %d %d "
680  "%d %d %d "
681  "%6.3f %6.3f %6.3f %6.3f "
682  "%d "
683  "%d %d %d "
684  "%d "
685  "%d %d %d "
686  "%6.3f %6.3f %6.3f "
687  "%d %d %6.3f %6.3f "
688  "%6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f "
689  "%6.3f %6.3f %6.3f %6.3f %6.3f "
690  "%6.6f %6.6f %6.6f %6.6f %6.6f "
691  "%6.3f %6.3f %6.3f %6.3f %6.3f "
692  "%6.6f %6.6f %6.6f %6.6f %6.6f "
693  "%6.3f %6.3f %6.3f "
694  "%6.3f"
695  "\n",
697  L.layer_id(), L.is_barrel(), hi_orig,
698  itrack, m_CandIdx(itrack, 0, 0), m_Label(itrack, 0, 0),
699  1.0f / m_Par[iI].At(itrack, 3, 0), getEta(m_Par[iI].At(itrack, 5, 0)), m_Par[iI].At(itrack, 4, 0), m_Chi2(itrack, 0, 0),
700  m_NFoundHits(itrack, 0, 0),
701  m_SeedOriginIdx(itrack, 0, 0), seed_lbl, seed_mcid,
702  mchid,
703  st_isfindable, st_prodtype, st_label,
704  st_pt, st_eta, st_phi,
705  st_nhits, st_charge, st_r, st_z,
706  q, L.hit_q(hi), ddq, dq, phi, L.hit_phi(hi), ddphi, dphi,
707  tx, ty, tr, tphi, tz,
708  tex, tey, ter, tephi, tez,
709  hx, hy, hr, hphi, hz,
710  hex, hey, her, hephi, hez,
711  ht_dxy, ht_dz, ht_dphi,
712  hchi2);
713  }
714  }
715  // clang-format on
716 #endif
717 
718  if (ddq >= dq)
719  continue;
720  if (ddphi >= dphi)
721  continue;
722 
723  // MT: Removing extra check gives full efficiency ...
724  // and means our error estimations are wrong!
725  // Avi says we should have *minimal* search windows per layer.
726  // Also ... if bins are sufficiently small, we do not need the extra
727  // checks, see above.
728  m_XHitArr.At(itrack, m_XHitSize[itrack]++, 0) = hi_orig;
729  } else {
730  // MT: The following check alone makes more sense with spiral traversal,
731  // we'd be taking in closest hits first.
732 
733  // Hmmh -- there used to be some more checks here.
734  // Or, at least, the phi binning was much smaller and no further checks were done.
735  assert(false && "this code has not been used in a while -- see comments in code");
736 
737  if (m_XHitSize[itrack] < MPlexHitIdxMax) {
738  m_XHitArr.At(itrack, m_XHitSize[itrack]++, 0) = hi_orig;
739  }
740  }
741  } //hi
742  } //pi
743  } //qi
744  } //itrack
745  }
746 
747  //==============================================================================
748  // SelectHitIndicesV2
749  //==============================================================================
750 
751  void MkFinder::selectHitIndicesV2(const LayerOfHits &layer_of_hits, const int N_proc) {
752  // bool debug = true;
753  using bidx_t = LayerOfHits::bin_index_t;
754  using bcnt_t = LayerOfHits::bin_content_t;
755  const LayerOfHits &L = layer_of_hits;
756  const LayerInfo &LI = *L.layer_info();
757 
758  const int iI = iP;
759 
760  dprintf("LayerOfHits::SelectHitIndicesV2 %s layer=%d N_proc=%d\n",
761  L.is_barrel() ? "barrel" : "endcap",
762  L.layer_id(),
763  N_proc);
764 
765 #ifdef RNT_DUMP_MkF_SelHitIdcs
766  rnt_shi.InnerIdcsReset(N_proc);
767  for (int i = 0; i < N_proc; ++i) {
769  if (m_FailFlag[i]) {
770  rnt_shi.RegisterFailedProp(i, m_Par[1 - iI], m_Par[iI], m_event, m_SeedOriginIdx[i]);
771  } else if (slfh.is_set()) {
772  rnt_shi.RegisterGoodProp(i, m_Par[iI], m_event, m_SeedOriginIdx[i]);
773  // get BinSearch result from V1.
774  selectHitIndices(layer_of_hits, N_proc, true);
775  } // else ... could do something about the bad seeds ... probably better to collect elsewhere.
776  }
777 #endif
778 
779  constexpr int NEW_MAX_HIT = 6; // 4 - 6 give about the same # of tracks in quality-val
780  constexpr float DDPHI_PRESEL_FAC = 2.0f;
781  constexpr float DDQ_PRESEL_FAC = 1.2f;
782  constexpr float PHI_BIN_EXTRA_FAC = 2.75f;
783  constexpr float Q_BIN_EXTRA_FAC = 1.6f;
784 
785  namespace mp = mini_propagators;
786  struct Bins {
787  MPlexQUH q0, q1, q2, p1, p2;
788  mp::InitialStatePlex isp;
789  mp::StatePlex sp1, sp2;
790  int n_proc;
791 
792  MPlexQF dphi_track, dq_track; // 3 sigma track errors at initial state
793 
794  // debug & ntuple dump -- to be local in functions
795  MPlexQF phi_c, dphi;
796  MPlexQF q_c, qmin, qmax;
797 
798  Bins(const MPlexLV &par, const MPlexQI &chg, int np = NN) : isp(par, chg), n_proc(np) {}
799 
800  void prop_to_limits(const LayerInfo &li) {
801  // Positions 1 and 2 should really be by "propagation order", 1 is the closest/
802  // This should also work for backward propagation so not exactly trivial.
803  // Also, do not really need propagation to center.
804  if (li.is_barrel()) {
805  isp.propagate_to_r(mp::PA_Exact, li.rin(), sp1, true, n_proc);
806  isp.propagate_to_r(mp::PA_Exact, li.rout(), sp2, true, n_proc);
807  } else {
808  isp.propagate_to_z(mp::PA_Exact, li.zmin(), sp1, true, n_proc);
809  isp.propagate_to_z(mp::PA_Exact, li.zmax(), sp2, true, n_proc);
810  }
811  }
812 
813  void find_bin_ranges(const LayerInfo &li, const LayerOfHits &loh, const MPlexLS &err) {
814  // Below made members for debugging
815  // MPlexQF phi_c, dphi_min, dphi_max;
816  // phi_c = mp::fast_atan2(isp.y, isp.x); // calculated below as difference
817 
818  // Matriplex::min_max(sp1.dphi, sp2.dphi, dphi_min, dphi_max);
819  // the above is wrong: dalpha is not dphi --> renamed variable in State
820  MPlexQF xp1, xp2, pmin, pmax;
821  xp1 = mp::fast_atan2(sp1.y, sp1.x);
822  xp2 = mp::fast_atan2(sp2.y, sp2.x);
823  Matriplex::min_max(xp1, xp2, pmin, pmax);
824  // Matriplex::min_max(mp::fast_atan2(sp1.y, sp1.x), smp::fast_atan2(sp2.y, sp2.x), pmin, pmax);
825  MPlexQF dp = pmax - pmin;
826  phi_c = 0.5f * (pmax + pmin);
827  for (int ii = 0; ii < n_proc; ++ii) {
828  if (dp[ii] > Const::PI) {
829  std::swap(pmax[ii], pmin[ii]);
830  dp[ii] = Const::TwoPI - dp[ii];
831  phi_c[ii] = Const::PI - phi_c[ii];
832  }
833  dphi[ii] = 0.5f * dp[ii];
834  // printf("phic: %f p1: %f p2: %f pmin: %f pmax: %f dphi: %f\n",
835  // phi_c[ii], xp1[ii], xp2[ii], pmin[ii], pmax[ii], dphi[ii]);
836  }
837 
838  const auto calc_err_xy = [&](const MPlexQF &x, const MPlexQF &y) {
839  return x * x * err.ReduceFixedIJ(0, 0) + y * y * err.ReduceFixedIJ(1, 1) +
840  2.0f * x * y * err.ReduceFixedIJ(0, 1);
841  };
842 
843  // Calculate dphi_track, dq_track differs for barrel/endcap
844  MPlexQF r2_c = isp.x * isp.x + isp.y * isp.y;
845  MPlexQF r2inv_c = 1.0f / r2_c;
846  MPlexQF dphidx_c = -isp.y * r2inv_c;
847  MPlexQF dphidy_c = isp.x * r2inv_c;
848  dphi_track = 3.0f * calc_err_xy(dphidx_c, dphidy_c).abs().sqrt();
849 
850  // MPlexQF qmin, qmax;
851  if (li.is_barrel()) {
852  Matriplex::min_max(sp1.z, sp2.z, qmin, qmax);
853  q_c = isp.z;
854  dq_track = 3.0f * err.ReduceFixedIJ(2, 2).abs().sqrt();
855  } else {
856  Matriplex::min_max(Matriplex::hypot(sp1.x, sp1.y), Matriplex::hypot(sp2.x, sp2.y), qmin, qmax);
857  q_c = Matriplex::sqrt(r2_c);
858  dq_track = 3.0f * (r2inv_c * calc_err_xy(isp.x, isp.y).abs()).sqrt();
859  }
860 
861  for (int i = 0; i < p1.kTotSize; ++i) {
862  // Clamp crazy sizes. This actually only happens when prop-fail flag is set.
863  // const float dphi_clamp = 0.1;
864  // if (dphi_min[i] > 0.0f || dphi_min[i] < -dphi_clamp) dphi_min[i] = -dphi_clamp;
865  // if (dphi_max[i] < 0.0f || dphi_max[i] > dphi_clampf) dphi_max[i] = dphi_clamp;
866  p1[i] = loh.phiBinChecked(pmin[i] - dphi_track[i] - PHI_BIN_EXTRA_FAC * 0.0123f);
867  p2[i] = loh.phiBinChecked(pmax[i] + dphi_track[i] + PHI_BIN_EXTRA_FAC * 0.0123f);
868 
869  q0[i] = loh.qBinChecked(q_c[i]);
870  q1[i] = loh.qBinChecked(qmin[i] - dq_track[i] - Q_BIN_EXTRA_FAC * 0.5f * li.q_bin());
871  q2[i] = loh.qBinChecked(qmax[i] + dq_track[i] + Q_BIN_EXTRA_FAC * 0.5f * li.q_bin()) + 1;
872  }
873  }
874  };
875 
876  Bins B(m_Par[iI], m_Chg, N_proc);
877  B.prop_to_limits(LI);
878  B.find_bin_ranges(LI, L, m_Err[iI]);
879 
880  for (int i = 0; i < N_proc; ++i) {
881  m_XHitSize[i] = 0;
882  // Notify failure. Ideally should be detected before selectHitIndices().
883  if (m_FailFlag[i]) {
885  } else {
886  if (LI.is_barrel()) {
887  m_XWsrResult[i] = L.is_within_z_sensitive_region(B.q_c[i], 0.5f * (B.q2[i] - B.q1[i]));
888  } else {
889  m_XWsrResult[i] = L.is_within_r_sensitive_region(B.q_c[i], 0.5f * (B.q2[i] - B.q1[i]));
890  }
891  }
892  }
893 
894  // for (int i = 0; i < N_proc; ++i) {
895  // printf("BinCheck %c %+8.6f %+8.6f | %3d %3d - %3d %3d || | %2d %2d - %2d %2d\n", LI.is_barrel() ? 'B' : 'E',
896  // B.phi[i], B.dphi[i], B.p1[i], B.p2[i], pb1v[i], pb2v[i],
897  // B.q[i], B.dq[i], B.q1[i], B.q2[i], qb1v[i], qb2v[i]);
898  // }
899 
900 #ifdef RNT_DUMP_MkF_SelHitIdcs
901  for (auto i : rnt_shi.f_h_idcs) {
902  CandInfo &ci = (*rnt_shi.ci)[rnt_shi.f_h_remap[i]];
903  ci.bsn = BinSearch({B.phi_c[i],
904  B.dphi[i],
905  B.q_c[i],
906  0.5f * (B.q2[i] - B.q1[i]),
907  B.p1[i],
908  B.p2[i],
909  B.q1[i],
910  B.q2[i],
913  false});
914  ci.ps_min = statep2propstate(B.sp1, i);
915  ci.ps_max = statep2propstate(B.sp2, i);
916  }
917 #endif
918 
919  struct PQE {
920  float score;
921  unsigned int hit_index;
922  };
923  auto pqe_cmp = [](const PQE &a, const PQE &b) { return a.score < b.score; };
924  std::priority_queue<PQE, std::vector<PQE>, decltype(pqe_cmp)> pqueue(pqe_cmp);
925  int pqueue_size = 0;
926 
927  // Vectorizing this makes it run slower!
928  //#pragma omp simd
929  for (int itrack = 0; itrack < N_proc; ++itrack) {
930  if (m_FailFlag[itrack]) {
931  m_XWsrResult[itrack].m_wsr = WSR_Failed;
932  continue;
933  }
934 
935  if (m_XWsrResult[itrack].m_wsr == WSR_Outside) {
936  continue;
937  }
938 
939  // New binning -- known to be too restrictive, so scaled up. Probably esp. in stereo layers.
940  // Also, could take track covariance dphi / dq extras + known tilt stuff.
941  const bidx_t qb = B.q0[itrack];
942  const bidx_t qb1 = B.q1[itrack];
943  const bidx_t qb2 = B.q2[itrack];
944  const bidx_t pb1 = B.p1[itrack];
945  const bidx_t pb2 = B.p2[itrack];
946 
947  // clang-format off
948  dprintf(" %2d/%2d: %6.3f %6.3f %6.6f %7.5f %3u %3u %4u %4u\n",
949  L.layer_id(), itrack, qv[itrack], phi[itrack], dqv[itrack], dphiv[itrack],
950  qb1, qb2, pb1, pb2);
951  // clang-format on
952 
953  mp::InitialState mp_is(m_Par[iI], m_Chg, itrack);
954  mp::State mp_s;
955 
956  for (bidx_t qi = qb1; qi != qb2; ++qi) {
957  for (bidx_t pi = pb1; pi != pb2; pi = L.phiMaskApply(pi + 1)) {
958  // Limit to central Q-bin
959  if (qi == qb && L.isBinDead(pi, qi) == true) {
960  dprint("dead module for track in layer=" << L.layer_id() << " qb=" << qi << " pi=" << pi << " q=" << q
961  << " phi=" << phi);
962  m_XWsrResult[itrack].m_in_gap = true;
963  }
964 
965  // It might make sense to make first loop to extract bin indices
966  // and issue prefetches at the same time.
967  // Then enter vectorized loop to actually collect the hits in proper order.
968 
969  //SK: ~20x1024 bin sizes give mostly 1 hit per bin. Commented out for 128 bins or less
970  // #pragma nounroll
971  auto pbi = L.phiQBinContent(pi, qi);
972  for (bcnt_t hi = pbi.begin(); hi < pbi.end(); ++hi) {
973  // MT: Access into m_hit_zs and m_hit_phis is 1% run-time each.
974 
975  const unsigned int hi_orig = L.getOriginalHitIndex(hi);
976 
977  if (m_iteration_hit_mask && (*m_iteration_hit_mask)[hi_orig]) {
978  dprintf(
979  "Yay, denying masked hit on layer %u, hi %u, orig idx %u\n", L.layer_info()->layer_id(), hi, hi_orig);
980  continue;
981  }
982 
983  if (m_XHitSize[itrack] >= MPlexHitIdxMax)
984  break;
985 
986  float new_q, new_phi, new_ddphi, new_ddq;
987  bool prop_fail;
988 
989  if (L.is_barrel()) {
990  prop_fail = mp_is.propagate_to_r(mp::PA_Exact, L.hit_qbar(hi), mp_s, true);
991  new_q = mp_s.z;
992  } else {
993  prop_fail = mp_is.propagate_to_z(mp::PA_Exact, L.hit_qbar(hi), mp_s, true);
994  new_q = std::hypot(mp_s.x, mp_s.y);
995  }
996 
997  new_phi = vdt::fast_atan2f(mp_s.y, mp_s.x);
998  new_ddphi = cdist(std::abs(new_phi - L.hit_phi(hi)));
999  new_ddq = std::abs(new_q - L.hit_q(hi));
1000 
1001  bool dqdphi_presel = new_ddq < B.dq_track[itrack] + DDQ_PRESEL_FAC * L.hit_q_half_length(hi) &&
1002  new_ddphi < B.dphi_track[itrack] + DDPHI_PRESEL_FAC * 0.0123f;
1003 
1004  // clang-format off
1005  dprintf(" SHI %3u %4u %5u %6.3f %6.3f %6.4f %7.5f PROP-%s %s\n",
1006  qi, pi, hi, L.hit_q(hi), L.hit_phi(hi),
1007  ddq, ddphi, prop_fail ? "FAIL" : "OK", dqdphi_presel ? "PASS" : "REJECT");
1008  // clang-format on
1009 
1010  if (prop_fail || !dqdphi_presel)
1011  continue;
1012  if (pqueue_size < NEW_MAX_HIT) {
1013  pqueue.push({new_ddphi, hi_orig});
1014  ++pqueue_size;
1015  } else if (new_ddphi < pqueue.top().score) {
1016  pqueue.pop();
1017  pqueue.push({new_ddphi, hi_orig});
1018  }
1019  } //hi
1020  } //pi
1021  } //qi
1022 
1023  dprintf(" PQUEUE (%d)", pqueue_size);
1024  // Reverse hits so best dphis/scores come first in the hit-index list.
1025  m_XHitSize[itrack] = pqueue_size;
1026  while (pqueue_size) {
1027  --pqueue_size;
1028  m_XHitArr.At(itrack, pqueue_size, 0) = pqueue.top().hit_index;
1029  dprintf(" %d: %f %d", pqueue_size, pqueue.top().score, pqueue.top().hit_index);
1030  pqueue.pop();
1031  }
1032  dprintf("\n");
1033 
1034  } //itrack
1035  }
1036 
1037  //==============================================================================
1038  // AddBestHit - Best Hit Track Finding
1039  //==============================================================================
1040 
1041  void MkFinder::addBestHit(const LayerOfHits &layer_of_hits, const int N_proc, const FindingFoos &fnd_foos) {
1042  // debug = true;
1043 
1044  MatriplexHitPacker mhp(layer_of_hits.hitArray());
1045 
1046  float minChi2[NN];
1047  int bestHit[NN];
1048  int maxSize = 0;
1049 
1050  // Determine maximum number of hits for tracks in the collection.
1051  for (int it = 0; it < NN; ++it) {
1052  if (it < N_proc) {
1053  if (m_XHitSize[it] > 0) {
1055  }
1056  }
1057 
1058  bestHit[it] = -1;
1059  minChi2[it] = getHitSelDynamicChi2Cut(it, iP);
1060  }
1061 
1062  for (int hit_cnt = 0; hit_cnt < maxSize; ++hit_cnt) {
1063  //fixme what if size is zero???
1064 
1065  mhp.reset();
1066 
1067  //#pragma omp simd doesn't vectorize with current compilers
1068  for (int itrack = 0; itrack < N_proc; ++itrack) {
1069  if (hit_cnt < m_XHitSize[itrack]) {
1070  mhp.addInputAt(itrack, layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0)));
1071  }
1072  }
1073 
1074  mhp.pack(m_msErr, m_msPar);
1075 
1076  //now compute the chi2 of track state vs hit
1077  MPlexQF outChi2;
1078  MPlexLV tmpPropPar;
1079  clearFailFlag();
1080  (*fnd_foos.m_compute_chi2_foo)(m_Err[iP],
1081  m_Par[iP],
1082  m_Chg,
1083  m_msErr,
1084  m_msPar,
1085  outChi2,
1086  tmpPropPar,
1087  m_FailFlag,
1088  N_proc,
1091 
1092  //update best hit in case chi2<minChi2
1093 #pragma omp simd
1094  for (int itrack = 0; itrack < N_proc; ++itrack) {
1095  if (hit_cnt < m_XHitSize[itrack]) {
1096  const float chi2 = std::abs(outChi2[itrack]); //fixme negative chi2 sometimes...
1097  dprint("chi2=" << chi2 << " minChi2[itrack]=" << minChi2[itrack]);
1098  if (chi2 < minChi2[itrack]) {
1099  minChi2[itrack] = chi2;
1100  bestHit[itrack] = m_XHitArr.At(itrack, hit_cnt, 0);
1101  }
1102  }
1103  }
1104  } // end loop over hits
1105 
1106  //#pragma omp simd
1107  for (int itrack = 0; itrack < N_proc; ++itrack) {
1108  if (m_XWsrResult[itrack].m_wsr == WSR_Outside) {
1109  // Why am I doing this?
1110  m_msErr.setDiagonal3x3(itrack, 666);
1111  m_msPar(itrack, 0, 0) = m_Par[iP](itrack, 0, 0);
1112  m_msPar(itrack, 1, 0) = m_Par[iP](itrack, 1, 0);
1113  m_msPar(itrack, 2, 0) = m_Par[iP](itrack, 2, 0);
1114 
1115  // XXXX If not in gap, should get back the old track params. But they are gone ...
1116  // Would actually have to do it right after SelectHitIndices where updated params are still ok.
1117  // Here they got screwed during hit matching.
1118  // So, I'd store them there (into propagated params) and retrieve them here.
1119  // Or we decide not to care ...
1120 
1121  continue;
1122  }
1123 
1124  //fixme decide what to do in case no hit found
1125  if (bestHit[itrack] >= 0) {
1126  const Hit &hit = layer_of_hits.refHit(bestHit[itrack]);
1127  const float chi2 = minChi2[itrack];
1128 
1129  dprint("ADD BEST HIT FOR TRACK #"
1130  << itrack << std::endl
1131  << "prop x=" << m_Par[iP].constAt(itrack, 0, 0) << " y=" << m_Par[iP].constAt(itrack, 1, 0) << std::endl
1132  << "copy in hit #" << bestHit[itrack] << " x=" << hit.position()[0] << " y=" << hit.position()[1]);
1133 
1134  m_msErr.copyIn(itrack, hit.errArray());
1135  m_msPar.copyIn(itrack, hit.posArray());
1136  m_Chi2(itrack, 0, 0) += chi2;
1137 
1138  add_hit(itrack, bestHit[itrack], layer_of_hits.layer_id());
1139  } else {
1140  int fake_hit_idx = Hit::kHitMissIdx;
1141 
1142  if (m_XWsrResult[itrack].m_wsr == WSR_Edge) {
1143  // YYYYYY Config::store_missed_layers
1144  fake_hit_idx = Hit::kHitEdgeIdx;
1145  } else if (num_all_minus_one_hits(itrack)) {
1146  fake_hit_idx = Hit::kHitStopIdx;
1147  }
1148 
1149  dprint("ADD FAKE HIT FOR TRACK #" << itrack << " withinBounds=" << (fake_hit_idx != Hit::kHitEdgeIdx)
1150  << " r=" << std::hypot(m_Par[iP](itrack, 0, 0), m_Par[iP](itrack, 1, 0)));
1151 
1152  m_msErr.setDiagonal3x3(itrack, 666);
1153  m_msPar(itrack, 0, 0) = m_Par[iP](itrack, 0, 0);
1154  m_msPar(itrack, 1, 0) = m_Par[iP](itrack, 1, 0);
1155  m_msPar(itrack, 2, 0) = m_Par[iP](itrack, 2, 0);
1156  // Don't update chi2
1157 
1158  add_hit(itrack, fake_hit_idx, layer_of_hits.layer_id());
1159  }
1160  }
1161 
1162  // Update the track parameters with this hit. (Note that some calculations
1163  // are already done when computing chi2. Not sure it's worth caching them?)
1164 
1165  dprint("update parameters");
1166  clearFailFlag();
1167  (*fnd_foos.m_update_param_foo)(m_Err[iP],
1168  m_Par[iP],
1169  m_Chg,
1170  m_msErr,
1171  m_msPar,
1172  m_Err[iC],
1173  m_Par[iC],
1174  m_FailFlag,
1175  N_proc,
1178 
1179  dprint("m_Par[iP](0,0,0)=" << m_Par[iP](0, 0, 0) << " m_Par[iC](0,0,0)=" << m_Par[iC](0, 0, 0));
1180  }
1181 
1182  //=======================================================
1183  // isStripQCompatible : check if prop is consistent with the barrel/endcap strip length
1184  //=======================================================
1186  int itrack, bool isBarrel, const MPlexLS &pErr, const MPlexLV &pPar, const MPlexHS &msErr, const MPlexHV &msPar) {
1187  //check module compatibility via long strip side = L/sqrt(12)
1188  if (isBarrel) { //check z direction only
1189  const float res = std::abs(msPar.constAt(itrack, 2, 0) - pPar.constAt(itrack, 2, 0));
1190  const float hitHL = sqrt(msErr.constAt(itrack, 2, 2) * 3.f); //half-length
1191  const float qErr = sqrt(pErr.constAt(itrack, 2, 2));
1192  dprint("qCompat " << hitHL << " + " << 3.f * qErr << " vs " << res);
1193  return hitHL + std::max(3.f * qErr, 0.5f) > res;
1194  } else { //project on xy, assuming the strip Length >> Width
1195  const float res[2]{msPar.constAt(itrack, 0, 0) - pPar.constAt(itrack, 0, 0),
1196  msPar.constAt(itrack, 1, 0) - pPar.constAt(itrack, 1, 0)};
1197  const float hitT2 = msErr.constAt(itrack, 0, 0) + msErr.constAt(itrack, 1, 1);
1198  const float hitT2inv = 1.f / hitT2;
1199  const float proj[3] = {msErr.constAt(itrack, 0, 0) * hitT2inv,
1200  msErr.constAt(itrack, 0, 1) * hitT2inv,
1201  msErr.constAt(itrack, 1, 1) * hitT2inv};
1202  const float qErr =
1203  sqrt(std::abs(pErr.constAt(itrack, 0, 0) * proj[0] + 2.f * pErr.constAt(itrack, 0, 1) * proj[1] +
1204  pErr.constAt(itrack, 1, 1) * proj[2])); //take abs to avoid non-pos-def cases
1205  const float resProj =
1206  sqrt(res[0] * proj[0] * res[0] + 2.f * res[1] * proj[1] * res[0] + res[1] * proj[2] * res[1]);
1207  dprint("qCompat " << sqrt(hitT2 * 3.f) << " + " << 3.f * qErr << " vs " << resProj);
1208  return sqrt(hitT2 * 3.f) + std::max(3.f * qErr, 0.5f) > resProj;
1209  }
1210  }
1211 
1212  //=======================================================
1213  // passStripChargePCMfromTrack : apply the slope correction to charge per cm and cut using hit err matrix
1214  // the raw pcm = charge/L_normal
1215  // the corrected qCorr = charge/L_path = charge/(L_normal*p/p_zLocal) = pcm*p_zLocal/p
1216  //=======================================================
1218  int itrack, bool isBarrel, unsigned int pcm, unsigned int pcmMin, const MPlexLV &pPar, const MPlexHS &msErr) {
1219  //skip the overflow case
1220  if (pcm >= Hit::maxChargePerCM())
1221  return true;
1222 
1223  float qSF;
1224  if (isBarrel) { //project in x,y, assuming zero-error direction is in this plane
1225  const float hitT2 = msErr.constAt(itrack, 0, 0) + msErr.constAt(itrack, 1, 1);
1226  const float hitT2inv = 1.f / hitT2;
1227  const float proj[3] = {msErr.constAt(itrack, 0, 0) * hitT2inv,
1228  msErr.constAt(itrack, 0, 1) * hitT2inv,
1229  msErr.constAt(itrack, 1, 1) * hitT2inv};
1230  const bool detXY_OK =
1231  std::abs(proj[0] * proj[2] - proj[1] * proj[1]) < 0.1f; //check that zero-direction is close
1232  const float cosP = cos(pPar.constAt(itrack, 4, 0));
1233  const float sinP = sin(pPar.constAt(itrack, 4, 0));
1234  const float sinT = std::abs(sin(pPar.constAt(itrack, 5, 0)));
1235  //qSF = sqrt[(px,py)*(1-proj)*(px,py)]/p = sinT*sqrt[(cosP,sinP)*(1-proj)*(cosP,sinP)].
1236  qSF = detXY_OK ? sinT * std::sqrt(std::abs(1.f + cosP * cosP * proj[0] + sinP * sinP * proj[2] -
1237  2.f * cosP * sinP * proj[1]))
1238  : 1.f;
1239  } else { //project on z
1240  // p_zLocal/p = p_z/p = cosT
1241  qSF = std::abs(cos(pPar.constAt(itrack, 5, 0)));
1242  }
1243 
1244  const float qCorr = pcm * qSF;
1245  dprint("pcm " << pcm << " * " << qSF << " = " << qCorr << " vs " << pcmMin);
1246  return qCorr > pcmMin;
1247  }
1248 
1249  //==============================================================================
1250  // FindCandidates - Standard Track Finding
1251  //==============================================================================
1252 
1253  void MkFinder::findCandidates(const LayerOfHits &layer_of_hits,
1254  std::vector<std::vector<TrackCand>> &tmp_candidates,
1255  const int offset,
1256  const int N_proc,
1257  const FindingFoos &fnd_foos) {
1258  // bool debug = true;
1259 
1260  MatriplexHitPacker mhp(layer_of_hits.hitArray());
1261 
1262  int maxSize = 0;
1263 
1264  // Determine maximum number of hits for tracks in the collection.
1265  for (int it = 0; it < NN; ++it) {
1266  if (it < N_proc) {
1267  if (m_XHitSize[it] > 0) {
1269  }
1270  }
1271  }
1272 
1273  dprintf("FindCandidates max hits to process=%d\n", maxSize);
1274 
1275  int nHitsAdded[NN]{};
1276  bool isTooLargeCluster[NN]{false};
1277 
1278  for (int hit_cnt = 0; hit_cnt < maxSize; ++hit_cnt) {
1279  mhp.reset();
1280 
1281  int charge_pcm[NN];
1282 
1283  //#pragma omp simd doesn't vectorize with current compilers
1284  for (int itrack = 0; itrack < N_proc; ++itrack) {
1285  if (hit_cnt < m_XHitSize[itrack]) {
1286  const auto &hit = layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0));
1287  mhp.addInputAt(itrack, hit);
1288  charge_pcm[itrack] = hit.chargePerCM();
1289  }
1290  }
1291 
1292  mhp.pack(m_msErr, m_msPar);
1293 
1294  //now compute the chi2 of track state vs hit
1295  MPlexQF outChi2;
1296  MPlexLV propPar;
1297  clearFailFlag();
1298 
1299  if (Config::usePropToPlane) {
1300  // Maybe could use 2 matriplex packers ... ModuleInfo has 3 * SVector3 and uint
1301  MPlexHV norm, dir;
1302  packModuleNormDir(layer_of_hits, hit_cnt, norm, dir, N_proc);
1304  m_Par[iP],
1305  m_Chg,
1306  m_msErr,
1307  m_msPar,
1308  norm,
1309  dir,
1310  outChi2,
1311  propPar,
1312  m_FailFlag,
1313  N_proc,
1316  } else {
1317  (*fnd_foos.m_compute_chi2_foo)(m_Err[iP],
1318  m_Par[iP],
1319  m_Chg,
1320  m_msErr,
1321  m_msPar,
1322  outChi2,
1323  propPar,
1324  m_FailFlag,
1325  N_proc,
1328  }
1329 
1330  // Now update the track parameters with this hit (note that some
1331  // calculations are already done when computing chi2, to be optimized).
1332  // 1. This is not needed for candidates the hit is not added to, but it's
1333  // vectorized so doing it serially below should take the same time.
1334  // 2. Still it's a waste of time in case the hit is not added to any of the
1335  // candidates, so check beforehand that at least one cand needs update.
1336  bool oneCandPassCut = false;
1337  for (int itrack = 0; itrack < N_proc; ++itrack) {
1338  float max_c2 = getHitSelDynamicChi2Cut(itrack, iP);
1339 
1340  if (hit_cnt < m_XHitSize[itrack]) {
1341  const float chi2 = std::abs(outChi2[itrack]); //fixme negative chi2 sometimes...
1342  dprint("chi2=" << chi2);
1343  if (chi2 < max_c2) {
1344  bool isCompatible = true;
1345  if (!layer_of_hits.is_pixel()) {
1346  //check module compatibility via long strip side = L/sqrt(12)
1347  isCompatible =
1348  isStripQCompatible(itrack, layer_of_hits.is_barrel(), m_Err[iP], propPar, m_msErr, m_msPar);
1349 
1350  //rescale strip charge to track parameters and reapply the cut
1351  isCompatible &= passStripChargePCMfromTrack(
1352  itrack, layer_of_hits.is_barrel(), charge_pcm[itrack], Hit::minChargePerCM(), propPar, m_msErr);
1353  }
1354  // Select only SiStrip hits with cluster size < maxClusterSize
1355  if (!layer_of_hits.is_pixel()) {
1356  if (layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0)).spanRows() >=
1358  isTooLargeCluster[itrack] = true;
1359  isCompatible = false;
1360  }
1361  }
1362 
1363  if (isCompatible) {
1364  oneCandPassCut = true;
1365  break;
1366  }
1367  }
1368  }
1369  }
1370 
1371  if (oneCandPassCut) {
1372  MPlexQI tmpChg = m_Chg;
1373  clearFailFlag();
1374  (*fnd_foos.m_update_param_foo)(m_Err[iP],
1375  m_Par[iP],
1376  tmpChg,
1377  m_msErr,
1378  m_msPar,
1379  m_Err[iC],
1380  m_Par[iC],
1381  m_FailFlag,
1382  N_proc,
1385 
1386  dprint("update parameters" << std::endl
1387  << "propagated track parameters x=" << m_Par[iP].constAt(0, 0, 0)
1388  << " y=" << m_Par[iP].constAt(0, 1, 0) << std::endl
1389  << " hit position x=" << m_msPar.constAt(0, 0, 0)
1390  << " y=" << m_msPar.constAt(0, 1, 0) << std::endl
1391  << " updated track parameters x=" << m_Par[iC].constAt(0, 0, 0)
1392  << " y=" << m_Par[iC].constAt(0, 1, 0));
1393 
1394  //create candidate with hit in case chi2 < max_c2
1395  //fixme: please vectorize me... (not sure it's possible in this case)
1396  for (int itrack = 0; itrack < N_proc; ++itrack) {
1397  float max_c2 = getHitSelDynamicChi2Cut(itrack, iP);
1398 
1399  if (hit_cnt < m_XHitSize[itrack]) {
1400  const float chi2 = std::abs(outChi2[itrack]); //fixme negative chi2 sometimes...
1401  dprint("chi2=" << chi2);
1402  if (chi2 < max_c2) {
1403  bool isCompatible = true;
1404  if (!layer_of_hits.is_pixel()) {
1405  //check module compatibility via long strip side = L/sqrt(12)
1406  isCompatible =
1407  isStripQCompatible(itrack, layer_of_hits.is_barrel(), m_Err[iP], propPar, m_msErr, m_msPar);
1408 
1409  //rescale strip charge to track parameters and reapply the cut
1410  isCompatible &= passStripChargePCMfromTrack(
1411  itrack, layer_of_hits.is_barrel(), charge_pcm[itrack], Hit::minChargePerCM(), propPar, m_msErr);
1412  }
1413  // Select only SiStrip hits with cluster size < maxClusterSize
1414  if (!layer_of_hits.is_pixel()) {
1415  if (layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0)).spanRows() >=
1417  isCompatible = false;
1418  }
1419 
1420  if (isCompatible) {
1421  bool hitExists = false;
1422  int maxHits = m_NFoundHits(itrack, 0, 0);
1423  if (layer_of_hits.is_pixel()) {
1424  for (int i = 0; i <= maxHits; ++i) {
1425  if (i > 2)
1426  break;
1427  if (m_HoTArrs[itrack][i].layer == layer_of_hits.layer_id()) {
1428  hitExists = true;
1429  break;
1430  }
1431  }
1432  }
1433  if (hitExists)
1434  continue;
1435 
1436  nHitsAdded[itrack]++;
1437  dprint("chi2 cut passed, creating new candidate");
1438  // Create a new candidate and fill the tmp_candidates output vector.
1439  // QQQ only instantiate if it will pass, be better than N_best
1440 
1441  const int hit_idx = m_XHitArr.At(itrack, hit_cnt, 0);
1442 
1443  TrackCand newcand;
1444  copy_out(newcand, itrack, iC);
1445  newcand.setCharge(tmpChg(itrack, 0, 0));
1446  newcand.addHitIdx(hit_idx, layer_of_hits.layer_id(), chi2);
1448  newcand,
1449  true /*penalizeTailMissHits*/,
1450  true /*inFindCandidates*/));
1451  newcand.setOriginIndex(m_CandIdx(itrack, 0, 0));
1452 
1453  // To apply a fixed cut instead of dynamic cut for overlap: m_iteration_params->chi2CutOverlap
1454  if (chi2 < max_c2) {
1455  CombCandidate &ccand = *newcand.combCandidate();
1456  ccand[m_CandIdx(itrack, 0, 0)].considerHitForOverlap(
1457  hit_idx, layer_of_hits.refHit(hit_idx).detIDinLayer(), chi2);
1458  }
1459 
1460  dprint("updated track parameters x=" << newcand.parameters()[0] << " y=" << newcand.parameters()[1]
1461  << " z=" << newcand.parameters()[2]
1462  << " pt=" << 1. / newcand.parameters()[3]);
1463 
1464  tmp_candidates[m_SeedIdx(itrack, 0, 0) - offset].emplace_back(newcand);
1465  }
1466  }
1467  }
1468  }
1469  } //end if (oneCandPassCut)
1470 
1471  } //end loop over hits
1472 
1473  //now add invalid hit
1474  //fixme: please vectorize me...
1475  for (int itrack = 0; itrack < N_proc; ++itrack) {
1476  // Cands that miss the layer are stashed away in MkBuilder(), before propagation,
1477  // and then merged back afterwards.
1478  if (m_XWsrResult[itrack].m_wsr == WSR_Outside) {
1479  continue;
1480  }
1481 
1482  int fake_hit_idx = ((num_all_minus_one_hits(itrack) < m_iteration_params->maxHolesPerCand) &&
1485  : Hit::kHitStopIdx;
1486 
1487  if (m_XWsrResult[itrack].m_wsr == WSR_Edge) {
1488  // YYYYYY m_iteration_params->store_missed_layers
1489  fake_hit_idx = Hit::kHitEdgeIdx;
1490  }
1491  //now add fake hit for tracks that passsed through inactive modules
1492  else if (m_XWsrResult[itrack].m_in_gap == true && nHitsAdded[itrack] == 0) {
1493  fake_hit_idx = Hit::kHitInGapIdx;
1494  }
1495  //now add fake hit for cases where hit cluster size is larger than maxClusterSize
1496  else if (isTooLargeCluster[itrack] == true && nHitsAdded[itrack] == 0) {
1497  fake_hit_idx = Hit::kHitMaxClusterIdx;
1498  }
1499 
1500  dprint("ADD FAKE HIT FOR TRACK #" << itrack << " withinBounds=" << (fake_hit_idx != Hit::kHitEdgeIdx)
1501  << " r=" << std::hypot(m_Par[iP](itrack, 0, 0), m_Par[iP](itrack, 1, 0)));
1502 
1503  // QQQ as above, only create and add if score better
1504  TrackCand newcand;
1505  copy_out(newcand, itrack, iP);
1506  newcand.addHitIdx(fake_hit_idx, layer_of_hits.layer_id(), 0.);
1507  newcand.setScore(getScoreCand(
1508  m_steering_params->m_track_scorer, newcand, true /*penalizeTailMissHits*/, true /*inFindCandidates*/));
1509  // Only relevant when we actually add a hit
1510  // newcand.setOriginIndex(m_CandIdx(itrack, 0, 0));
1511  tmp_candidates[m_SeedIdx(itrack, 0, 0) - offset].emplace_back(newcand);
1512  }
1513  }
1514 
1515  //==============================================================================
1516  // FindCandidatesCloneEngine - Clone Engine Track Finding
1517  //==============================================================================
1518 
1520  CandCloner &cloner,
1521  const int offset,
1522  const int N_proc,
1523  const FindingFoos &fnd_foos) {
1524  // bool debug = true;
1525 
1526  MatriplexHitPacker mhp(layer_of_hits.hitArray());
1527 
1528  int maxSize = 0;
1529 
1530  // Determine maximum number of hits for tracks in the collection.
1531 #pragma omp simd
1532  for (int it = 0; it < NN; ++it) {
1533  if (it < N_proc) {
1534  if (m_XHitSize[it] > 0) {
1536  }
1537  }
1538  }
1539 
1540  dprintf("FindCandidatesCloneEngine max hits to process=%d\n", maxSize);
1541 
1542  int nHitsAdded[NN]{};
1543  bool isTooLargeCluster[NN]{false};
1544 
1545  for (int hit_cnt = 0; hit_cnt < maxSize; ++hit_cnt) {
1546  mhp.reset();
1547 
1548  int charge_pcm[NN];
1549 
1550  //#pragma omp simd doesn't vectorize with current compilers
1551  for (int itrack = 0; itrack < N_proc; ++itrack) {
1552  if (hit_cnt < m_XHitSize[itrack]) {
1553  const auto &hit = layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0));
1554  mhp.addInputAt(itrack, hit);
1555  charge_pcm[itrack] = hit.chargePerCM();
1556  }
1557  }
1558 
1559  mhp.pack(m_msErr, m_msPar);
1560 
1561  //now compute the chi2 of track state vs hit
1562  MPlexQF outChi2;
1563  MPlexLV propPar;
1564  clearFailFlag();
1565 
1566  if (Config::usePropToPlane) {
1567  // Maybe could use 2 matriplex packers ... ModuleInfo has 3 * SVector3 and uint
1568  MPlexHV norm, dir;
1569  packModuleNormDir(layer_of_hits, hit_cnt, norm, dir, N_proc);
1571  m_Par[iP],
1572  m_Chg,
1573  m_msErr,
1574  m_msPar,
1575  norm,
1576  dir,
1577  outChi2,
1578  propPar,
1579  m_FailFlag,
1580  N_proc,
1583  } else {
1584  (*fnd_foos.m_compute_chi2_foo)(m_Err[iP],
1585  m_Par[iP],
1586  m_Chg,
1587  m_msErr,
1588  m_msPar,
1589  outChi2,
1590  propPar,
1591  m_FailFlag,
1592  N_proc,
1595  }
1596 
1597  //#pragma omp simd // DOES NOT VECTORIZE AS IT IS NOW
1598  for (int itrack = 0; itrack < N_proc; ++itrack) {
1599  // We can be in failed state from the initial propagation before selectHitIndices
1600  // and there hit_count for track is set to -1 and WSR state to Failed, handled below.
1601  // Or we might have hit it here in propagate-to-hit.
1602  // PROP-FAIL-ENABLE FailFlag check to be enabled when propagation failure
1603  // detection is properly implemented in propagate-to-R/Z.
1604  if ( hit_cnt < m_XHitSize[itrack]) {
1605  // make sure the hit was in the compatiblity window for the candidate
1606  const float max_c2 = getHitSelDynamicChi2Cut(itrack, iP);
1607  const float chi2 = std::abs(outChi2[itrack]); //fixme negative chi2 sometimes...
1608  // XXX-NUM-ERR assert(chi2 >= 0);
1609 
1610  dprint("chi2=" << chi2 << " for trkIdx=" << itrack << " hitIdx=" << m_XHitArr.At(itrack, hit_cnt, 0));
1611  if (chi2 < max_c2) {
1612  bool isCompatible = true;
1613  if (!layer_of_hits.is_pixel()) {
1614  //check module compatibility via long strip side = L/sqrt(12)
1615  isCompatible =
1616  isStripQCompatible(itrack, layer_of_hits.is_barrel(), m_Err[iP], propPar, m_msErr, m_msPar);
1617 
1618  //rescale strip charge to track parameters and reapply the cut
1619  isCompatible &= passStripChargePCMfromTrack(
1620  itrack, layer_of_hits.is_barrel(), charge_pcm[itrack], Hit::minChargePerCM(), propPar, m_msErr);
1621  }
1622 
1623  // Select only SiStrip hits with cluster size < maxClusterSize
1624  if (!layer_of_hits.is_pixel()) {
1625  if (layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0)).spanRows() >=
1627  isTooLargeCluster[itrack] = true;
1628  isCompatible = false;
1629  }
1630  }
1631 
1632  if (isCompatible) {
1633  CombCandidate &ccand = cloner.combCandWithOriginalIndex(m_SeedIdx(itrack, 0, 0));
1634  bool hitExists = false;
1635  int maxHits = m_NFoundHits(itrack, 0, 0);
1636  if (layer_of_hits.is_pixel()) {
1637  for (int i = 0; i <= maxHits; ++i) {
1638  if (i > 2)
1639  break;
1640  if (ccand.hot(i).layer == layer_of_hits.layer_id()) {
1641  hitExists = true;
1642  break;
1643  }
1644  }
1645  }
1646  if (hitExists)
1647  continue;
1648 
1649  nHitsAdded[itrack]++;
1650  const int hit_idx = m_XHitArr.At(itrack, hit_cnt, 0);
1651 
1652  // Register hit for overlap consideration, if chi2 cut is passed
1653  // To apply a fixed cut instead of dynamic cut for overlap: m_iteration_params->chi2CutOverlap
1654  if (chi2 < max_c2) {
1655  ccand[m_CandIdx(itrack, 0, 0)].considerHitForOverlap(
1656  hit_idx, layer_of_hits.refHit(hit_idx).detIDinLayer(), chi2);
1657  }
1658 
1659  IdxChi2List tmpList;
1660  tmpList.trkIdx = m_CandIdx(itrack, 0, 0);
1661  tmpList.hitIdx = hit_idx;
1662  tmpList.module = layer_of_hits.refHit(hit_idx).detIDinLayer();
1663  tmpList.nhits = m_NFoundHits(itrack, 0, 0) + 1;
1664  tmpList.ntailholes = 0;
1665  tmpList.noverlaps = m_NOverlapHits(itrack, 0, 0);
1666  tmpList.nholes = num_all_minus_one_hits(itrack);
1667  tmpList.pt = std::abs(1.0f / m_Par[iP].At(itrack, 3, 0));
1668  tmpList.chi2 = m_Chi2(itrack, 0, 0) + chi2;
1669  tmpList.chi2_hit = chi2;
1671  cloner.add_cand(m_SeedIdx(itrack, 0, 0) - offset, tmpList);
1672 
1673  dprint(" adding hit with hit_cnt=" << hit_cnt << " for trkIdx=" << tmpList.trkIdx
1674  << " orig Seed=" << m_Label(itrack, 0, 0));
1675  }
1676  }
1677  }
1678  }
1679 
1680  } //end loop over hits
1681 
1682  //now add invalid hit
1683  for (int itrack = 0; itrack < N_proc; ++itrack) {
1684  dprint("num_all_minus_one_hits(" << itrack << ")=" << num_all_minus_one_hits(itrack));
1685 
1686  // Cands that miss the layer are stashed away in MkBuilder(), before propagation,
1687  // and then merged back afterwards.
1688  if (m_XWsrResult[itrack].m_wsr == WSR_Outside) {
1689  continue;
1690  }
1691 
1692  // int fake_hit_idx = num_all_minus_one_hits(itrack) < m_iteration_params->maxHolesPerCand ? -1 : -2;
1693  int fake_hit_idx = ((num_all_minus_one_hits(itrack) < m_iteration_params->maxHolesPerCand) &&
1696  : Hit::kHitStopIdx;
1697 
1698  if (m_XWsrResult[itrack].m_wsr == WSR_Edge) {
1699  fake_hit_idx = Hit::kHitEdgeIdx;
1700  }
1701  //now add fake hit for tracks that passsed through inactive modules
1702  else if (m_XWsrResult[itrack].m_in_gap == true && nHitsAdded[itrack] == 0) {
1703  fake_hit_idx = Hit::kHitInGapIdx;
1704  }
1705  //now add fake hit for cases where hit cluster size is larger than maxClusterSize
1706  else if (isTooLargeCluster[itrack] == true && nHitsAdded[itrack] == 0) {
1707  fake_hit_idx = Hit::kHitMaxClusterIdx;
1708  }
1709 
1710  // PROP-FAIL-ENABLE The following to be enabled when propagation failure
1711  // detection is properly implemented in propagate-to-R/Z.
1712  // // Override for failed propagation, this trumps all other cases.
1713  // if (m_XWsrResult[itrack].m_wsr == WSR_Failed) {
1714  // fake_hit_idx = Hit::kHitStopIdx;
1715  // }
1716 
1717  IdxChi2List tmpList;
1718  tmpList.trkIdx = m_CandIdx(itrack, 0, 0);
1719  tmpList.hitIdx = fake_hit_idx;
1720  tmpList.module = -1;
1721  tmpList.nhits = m_NFoundHits(itrack, 0, 0);
1722  tmpList.ntailholes = (fake_hit_idx == Hit::kHitMissIdx ? m_NTailMinusOneHits(itrack, 0, 0) + 1
1723  : m_NTailMinusOneHits(itrack, 0, 0));
1724  tmpList.noverlaps = m_NOverlapHits(itrack, 0, 0);
1725  tmpList.nholes = num_inside_minus_one_hits(itrack);
1726  tmpList.pt = std::abs(1.0f / m_Par[iP].At(itrack, 3, 0));
1727  tmpList.chi2 = m_Chi2(itrack, 0, 0);
1728  tmpList.chi2_hit = 0;
1730  cloner.add_cand(m_SeedIdx(itrack, 0, 0) - offset, tmpList);
1731  dprint("adding invalid hit " << fake_hit_idx);
1732  }
1733  }
1734 
1735  //==============================================================================
1736  // UpdateWithLoadedHit
1737  //==============================================================================
1738 
1739  void MkFinder::updateWithLoadedHit(int N_proc, const LayerOfHits &layer_of_hits, const FindingFoos &fnd_foos) {
1740  // See comment in MkBuilder::find_tracks_in_layer() about intra / inter flags used here
1741  // for propagation to the hit.
1742  clearFailFlag();
1743  if (Config::usePropToPlane) {
1744  MPlexHV norm, dir;
1745  packModuleNormDir(layer_of_hits, 0, norm, dir, N_proc);
1747  m_Par[iP],
1748  m_Chg,
1749  m_msErr,
1750  m_msPar,
1751  norm,
1752  dir,
1753  m_Err[iC],
1754  m_Par[iC],
1755  m_FailFlag,
1756  N_proc,
1759  } else {
1760  (*fnd_foos.m_update_param_foo)(m_Err[iP],
1761  m_Par[iP],
1762  m_Chg,
1763  m_msErr,
1764  m_msPar,
1765  m_Err[iC],
1766  m_Par[iC],
1767  m_FailFlag,
1768  N_proc,
1771  }
1772 
1773  // PROP-FAIL-ENABLE The following to be enabled when propagation failure
1774  // detection is properly implemented in propagate-to-R/Z.
1775  // for (int i = 0; i < N_proc; ++i) {
1776  // if (m_FailFlag[i]) {
1777  // dprintf("MkFinder::updateWithLoadedHit fail in update, recovering.\n");
1778  // m_Err[iC].copySlot(i, m_Err[iP]);
1779  // m_Par[iC].copySlot(i, m_Par[iP]);
1780  // }
1781  // }
1782  }
1783 
1784  void MkFinder::chi2OfLoadedHit(int N_proc, const FindingFoos &fnd_foos) {
1785  // We expect input in iC slots from above function.
1786  // See comment in MkBuilder::find_tracks_in_layer() about intra / inter flags used here
1787  // for propagation to the hit.
1788  clearFailFlag();
1789  (*fnd_foos.m_compute_chi2_foo)(m_Err[iC],
1790  m_Par[iC],
1791  m_Chg,
1792  m_msErr,
1793  m_msPar,
1794  m_Chi2,
1795  m_Par[iP],
1796  m_FailFlag,
1797  N_proc,
1800 
1801  // PROP-FAIL-ENABLE .... removed here
1802  }
1803 
1804  //==============================================================================
1805  // CopyOutParErr
1806  //==============================================================================
1807 
1808  void MkFinder::copyOutParErr(std::vector<CombCandidate> &seed_cand_vec, int N_proc, bool outputProp) const {
1809  const int iO = outputProp ? iP : iC;
1810 
1811  for (int i = 0; i < N_proc; ++i) {
1812  TrackCand &cand = seed_cand_vec[m_SeedIdx(i, 0, 0)][m_CandIdx(i, 0, 0)];
1813 
1814  // Set the track state to the updated parameters
1815  m_Err[iO].copyOut(i, cand.errors_nc().Array());
1816  m_Par[iO].copyOut(i, cand.parameters_nc().Array());
1817  cand.setCharge(m_Chg(i, 0, 0));
1818 
1819  dprint((outputProp ? "propagated" : "updated")
1820  << " track parameters x=" << cand.parameters()[0] << " y=" << cand.parameters()[1]
1821  << " z=" << cand.parameters()[2] << " pt=" << 1. / cand.parameters()[3] << " posEta=" << cand.posEta());
1822  }
1823  }
1824 
1825  //==============================================================================
1826  // Backward Fit hack
1827  //==============================================================================
1828 
1829  void MkFinder::bkFitInputTracks(TrackVec &cands, int beg, int end) {
1830  // Uses HitOnTrack vector from Track directly + a local cursor array to current hit.
1831 
1832  MatriplexTrackPacker mtp(&cands[beg]);
1833 
1834  int itrack = 0;
1835 
1836  for (int i = beg; i < end; ++i, ++itrack) {
1837  const Track &trk = cands[i];
1838 
1839  m_Chg(itrack, 0, 0) = trk.charge();
1840  m_CurHit[itrack] = trk.nTotalHits() - 1;
1841  m_HoTArr[itrack] = trk.getHitsOnTrackArray();
1842 
1843  mtp.addInput(trk);
1844  }
1845 
1846  m_Chi2.setVal(0);
1847 
1848  mtp.pack(m_Err[iC], m_Par[iC]);
1849 
1850  m_Err[iC].scale(100.0f);
1851  }
1852 
1853  void MkFinder::bkFitInputTracks(EventOfCombCandidates &eocss, int beg, int end) {
1854  // Could as well use HotArrays from tracks directly + a local cursor array to last hit.
1855 
1856  // XXXX - shall we assume only TrackCand-zero is needed and that we can freely
1857  // bork the HoTNode array?
1858 
1859  MatriplexTrackPacker mtp(&eocss[beg][0]);
1860 
1861  int itrack = 0;
1862 
1863  for (int i = beg; i < end; ++i, ++itrack) {
1864  const TrackCand &trk = eocss[i][0];
1865 
1866  m_Chg(itrack, 0, 0) = trk.charge();
1867  m_CurNode[itrack] = trk.lastCcIndex();
1868  m_HoTNodeArr[itrack] = trk.combCandidate()->hotsData();
1869 
1870  // XXXX Need TrackCand* to update num-hits. Unless I collect info elsewhere
1871  // and fix it in BkFitOutputTracks.
1872  m_TrkCand[itrack] = &eocss[i][0];
1873 
1874  mtp.addInput(trk);
1875  }
1876 
1877  m_Chi2.setVal(0);
1878 
1879  mtp.pack(m_Err[iC], m_Par[iC]);
1880 
1881  m_Err[iC].scale(100.0f);
1882  }
1883 
1884  //------------------------------------------------------------------------------
1885 
1886  void MkFinder::bkFitOutputTracks(TrackVec &cands, int beg, int end, bool outputProp) {
1887  // Only copy out track params / errors / chi2, all the rest is ok.
1888 
1889  const int iO = outputProp ? iP : iC;
1890 
1891  int itrack = 0;
1892  for (int i = beg; i < end; ++i, ++itrack) {
1893  Track &trk = cands[i];
1894 
1895  m_Err[iO].copyOut(itrack, trk.errors_nc().Array());
1896  m_Par[iO].copyOut(itrack, trk.parameters_nc().Array());
1897 
1898  trk.setChi2(m_Chi2(itrack, 0, 0));
1899  if (isFinite(trk.chi2())) {
1901  }
1902  }
1903  }
1904 
1905  void MkFinder::bkFitOutputTracks(EventOfCombCandidates &eocss, int beg, int end, bool outputProp) {
1906  // Only copy out track params / errors / chi2, all the rest is ok.
1907 
1908  // XXXX - where will rejected hits get removed?
1909 
1910  const int iO = outputProp ? iP : iC;
1911 
1912  int itrack = 0;
1913  for (int i = beg; i < end; ++i, ++itrack) {
1914  TrackCand &trk = eocss[i][0];
1915 
1916  m_Err[iO].copyOut(itrack, trk.errors_nc().Array());
1917  m_Par[iO].copyOut(itrack, trk.parameters_nc().Array());
1918 
1919  trk.setChi2(m_Chi2(itrack, 0, 0));
1920  if (isFinite(trk.chi2())) {
1922  }
1923  }
1924  }
1925 
1926  //------------------------------------------------------------------------------
1927 
1928 #if defined(DEBUG_BACKWARD_FIT) || defined(DEBUG_BACKWARD_FIT_BH)
1929  namespace {
1930  float e2s(float x) { return 1e4 * std::sqrt(x); }
1931  } // namespace
1932 #endif
1933 
1934  void MkFinder::bkFitFitTracksBH(const EventOfHits &eventofhits,
1935  const SteeringParams &st_par,
1936  const int N_proc,
1937  bool chiDebug) {
1938  // Prototyping final backward fit.
1939  // This works with track-finding indices, before remapping.
1940  //
1941  // Layers should be collected during track finding and list all layers that have actual hits.
1942  // Then we could avoid checking which layers actually do have hits.
1943 
1944  MPlexQF tmp_chi2;
1945  float tmp_err[6] = {666, 0, 666, 0, 0, 666};
1946  float tmp_pos[3];
1947 
1948  for (auto lp_iter = st_par.m_layer_plan.rbegin(); lp_iter != st_par.m_layer_plan.rend(); ++lp_iter) {
1949  const int layer = lp_iter->m_layer;
1950 
1951  const LayerOfHits &L = eventofhits[layer];
1952  const LayerInfo &LI = *L.layer_info();
1953 
1954  int count = 0;
1955  for (int i = 0; i < N_proc; ++i) {
1956  while (m_CurHit[i] >= 0 && m_HoTArr[i][m_CurHit[i]].index < 0)
1957  --m_CurHit[i];
1958 
1959  if (m_CurHit[i] >= 0 && m_HoTArr[i][m_CurHit[i]].layer == layer) {
1960  // Skip the overlap hits -- if they exist.
1961  // 1. Overlap hit gets placed *after* the original hit in TrackCand::exportTrack()
1962  // which is *before* in the reverse iteration that we are doing here.
1963  // 2. Seed-hit merging can result in more than two hits per layer.
1964  while (m_CurHit[i] > 0 && m_HoTArr[i][m_CurHit[i] - 1].layer == layer)
1965  --m_CurHit[i];
1966 
1967  const Hit &hit = L.refHit(m_HoTArr[i][m_CurHit[i]].index);
1968  m_msErr.copyIn(i, hit.errArray());
1969  m_msPar.copyIn(i, hit.posArray());
1970  ++count;
1971  --m_CurHit[i];
1972  } else {
1973  tmp_pos[0] = m_Par[iC](i, 0, 0);
1974  tmp_pos[1] = m_Par[iC](i, 1, 0);
1975  tmp_pos[2] = m_Par[iC](i, 2, 0);
1976  m_msErr.copyIn(i, tmp_err);
1977  m_msPar.copyIn(i, tmp_pos);
1978  }
1979  }
1980 
1981  if (count == 0)
1982  continue;
1983 
1984  // ZZZ Could add missing hits here, only if there are any actual matches.
1985 
1986  if (LI.is_barrel()) {
1988 
1990  m_Err[iP],
1991  m_Par[iP],
1992  m_msErr,
1993  m_msPar,
1994  m_Err[iC],
1995  m_Par[iC],
1996  tmp_chi2,
1997  N_proc);
1998  } else {
2000 
2002  m_Err[iP],
2003  m_Par[iP],
2004  m_msErr,
2005  m_msPar,
2006  m_Err[iC],
2007  m_Par[iC],
2008  tmp_chi2,
2009  N_proc);
2010  }
2011 
2012  //fixup invpt sign and charge
2013  for (int n = 0; n < N_proc; ++n) {
2014  if (m_Par[iC].At(n, 3, 0) < 0) {
2015  m_Chg.At(n, 0, 0) = -m_Chg.At(n, 0, 0);
2016  m_Par[iC].At(n, 3, 0) = -m_Par[iC].At(n, 3, 0);
2017  }
2018  }
2019 
2020 #ifdef DEBUG_BACKWARD_FIT_BH
2021  // Dump per hit chi2
2022  for (int i = 0; i < N_proc; ++i) {
2023  float r_h = std::hypot(m_msPar.At(i, 0, 0), m_msPar.At(i, 1, 0));
2024  float r_t = std::hypot(m_Par[iC].At(i, 0, 0), m_Par[iC].At(i, 1, 0));
2025 
2026  // if ((std::isnan(tmp_chi2[i]) || std::isnan(r_t)))
2027  // if ( ! std::isnan(tmp_chi2[i]) && tmp_chi2[i] > 0) // && tmp_chi2[i] > 30)
2028  if (chiDebug) {
2029  int ti = iP;
2030  printf(
2031  "CHIHIT %3d %10g %10g %10g %10g %10g %11.5g %11.5g %11.5g %10g %10g %10g %10g %11.5g %11.5g %11.5g %10g "
2032  "%10g %10g %10g %10g %11.5g %11.5g\n",
2033  layer,
2034  tmp_chi2[i],
2035  m_msPar.At(i, 0, 0),
2036  m_msPar.At(i, 1, 0),
2037  m_msPar.At(i, 2, 0),
2038  r_h, // x_h y_h z_h r_h -- hit pos
2039  e2s(m_msErr.At(i, 0, 0)),
2040  e2s(m_msErr.At(i, 1, 1)),
2041  e2s(m_msErr.At(i, 2, 2)), // ex_h ey_h ez_h -- hit errors
2042  m_Par[ti].At(i, 0, 0),
2043  m_Par[ti].At(i, 1, 0),
2044  m_Par[ti].At(i, 2, 0),
2045  r_t, // x_t y_t z_t r_t -- track pos
2046  e2s(m_Err[ti].At(i, 0, 0)),
2047  e2s(m_Err[ti].At(i, 1, 1)),
2048  e2s(m_Err[ti].At(i, 2, 2)), // ex_t ey_t ez_t -- track errors
2049  1.0f / m_Par[ti].At(i, 3, 0),
2050  m_Par[ti].At(i, 4, 0),
2051  m_Par[ti].At(i, 5, 0), // pt, phi, theta
2052  std::atan2(m_msPar.At(i, 1, 0), m_msPar.At(i, 0, 0)), // phi_h
2053  std::atan2(m_Par[ti].At(i, 1, 0), m_Par[ti].At(i, 0, 0)), // phi_t
2054  1e4f * std::hypot(m_msPar.At(i, 0, 0) - m_Par[ti].At(i, 0, 0),
2055  m_msPar.At(i, 1, 0) - m_Par[ti].At(i, 1, 0)), // d_xy
2056  1e4f * (m_msPar.At(i, 2, 0) - m_Par[ti].At(i, 2, 0)) // d_z
2057  // e2s((m_msErr.At(i,0,0) + m_msErr.At(i,1,1)) / (r_h * r_h)), // ephi_h
2058  // e2s((m_Err[ti].At(i,0,0) + m_Err[ti].At(i,1,1)) / (r_t * r_t)) // ephi_t
2059  );
2060  }
2061  }
2062 #endif
2063 
2064  // update chi2
2065  m_Chi2.add(tmp_chi2);
2066  }
2067  }
2068 
2069  //------------------------------------------------------------------------------
2070 
2071  void MkFinder::print_par_err(int corp, int mslot) const {
2072 #ifdef DEBUG
2073  printf("Parameters:\n");
2074  for (int i = 0; i < 6; ++i) {
2075  printf(" %12.4g", m_Par[corp].constAt(mslot, i, 0));
2076  }
2077  printf("\nError matrix\n");
2078  for (int i = 0; i < 6; ++i) {
2079  for (int j = 0; j < 6; ++j) {
2080  printf(" %12.4g", m_Err[corp].constAt(mslot, i, j));
2081  }
2082  printf("\n");
2083  }
2084 #endif
2085  }
2086 
2087  void MkFinder::bkFitFitTracks(const EventOfHits &eventofhits,
2088  const SteeringParams &st_par,
2089  const int N_proc,
2090  bool chiDebug) {
2091  // Prototyping final backward fit.
2092  // This works with track-finding indices, before remapping.
2093  //
2094  // Layers should be collected during track finding and list all layers that have actual hits.
2095  // Then we could avoid checking which layers actually do have hits.
2096 
2097  // bool debug = true;
2098 
2099  MPlexQF tmp_chi2;
2100  MPlexQI no_mat_effs;
2101  float tmp_err[6] = {666, 0, 666, 0, 0, 666};
2102  float tmp_pos[3];
2103 
2104 #if defined(DEBUG_PROP_UPDATE)
2105  const int DSLOT = 0;
2106  printf("bkfit entry, track in slot %d\n", DSLOT);
2107  print_par_err(iC, DSLOT);
2108 #endif
2109 
2110  for (auto lp_iter = st_par.make_iterator(SteeringParams::IT_BkwFit); lp_iter.is_valid(); ++lp_iter) {
2111  const int layer = lp_iter.layer();
2112 
2113  const LayerOfHits &L = eventofhits[layer];
2114  const LayerInfo &LI = *L.layer_info();
2115 
2116 #if defined(DEBUG_BACKWARD_FIT)
2117  const Hit *last_hit_ptr[NN];
2118 #endif
2119 
2120  no_mat_effs.setVal(0);
2121  int done_count = 0;
2122  int here_count = 0;
2123  for (int i = 0; i < N_proc; ++i) {
2124  while (m_CurNode[i] >= 0 && m_HoTNodeArr[i][m_CurNode[i]].m_hot.index < 0) {
2126  }
2127 
2128  if (m_CurNode[i] < 0)
2129  ++done_count;
2130 
2131  if (m_CurNode[i] >= 0 && m_HoTNodeArr[i][m_CurNode[i]].m_hot.layer == layer) {
2132  // Skip the overlap hits -- if they exist.
2133  // 1. Overlap hit gets placed *after* the original hit in TrackCand::exportTrack()
2134  // which is *before* in the reverse iteration that we are doing here.
2135  // 2. Seed-hit merging can result in more than two hits per layer.
2136  // while (m_CurHit[i] > 0 && m_HoTArr[ i ][ m_CurHit[i] - 1 ].layer == layer) --m_CurHit[i];
2137  while (m_HoTNodeArr[i][m_CurNode[i]].m_prev_idx >= 0 &&
2138  m_HoTNodeArr[i][m_HoTNodeArr[i][m_CurNode[i]].m_prev_idx].m_hot.layer == layer)
2140 
2141  const Hit &hit = L.refHit(m_HoTNodeArr[i][m_CurNode[i]].m_hot.index);
2142 
2143 #ifdef DEBUG_BACKWARD_FIT
2144  last_hit_ptr[i] = &hit;
2145 #endif
2146  m_msErr.copyIn(i, hit.errArray());
2147  m_msPar.copyIn(i, hit.posArray());
2148  ++here_count;
2149 
2151  } else {
2152 #ifdef DEBUG_BACKWARD_FIT
2153  last_hit_ptr[i] = nullptr;
2154 #endif
2155  no_mat_effs[i] = 1;
2156  tmp_pos[0] = m_Par[iC](i, 0, 0);
2157  tmp_pos[1] = m_Par[iC](i, 1, 0);
2158  tmp_pos[2] = m_Par[iC](i, 2, 0);
2159  m_msErr.copyIn(i, tmp_err);
2160  m_msPar.copyIn(i, tmp_pos);
2161  }
2162  }
2163 
2164  if (done_count == N_proc)
2165  break;
2166  if (here_count == 0)
2167  continue;
2168 
2169  // ZZZ Could add missing hits here, only if there are any actual matches.
2170 
2171  clearFailFlag();
2172 
2173  // PROP-FAIL-ENABLE Once always "copy input to output on fail" is removed from
2174  // propagateToR one might want to enable this for barrel or endcap or both.
2175  if (LI.is_barrel()) {
2177 
2179  m_Err[iP],
2180  m_Par[iP],
2181  m_msErr,
2182  m_msPar,
2183  m_Err[iC],
2184  m_Par[iC],
2185  tmp_chi2,
2186  N_proc);
2187  } else {
2189 
2191  m_Err[iP],
2192  m_Par[iP],
2193  m_msErr,
2194  m_msPar,
2195  m_Err[iC],
2196  m_Par[iC],
2197  tmp_chi2,
2198  N_proc);
2199  }
2200 
2201 #if defined(DEBUG_PROP_UPDATE)
2202  printf("\nbkfit at layer %d, track in slot %d -- fail=%d, had hit=%d (%g, %g, %g)\n",
2203  LI.layer_id(),
2204  DSLOT,
2205  m_FailFlag[DSLOT],
2206  1 - no_mat_effs[DSLOT],
2207  m_msPar(DSLOT, 0, 0),
2208  m_msPar(DSLOT, 1, 0),
2209  m_msPar(DSLOT, 2, 0));
2210  printf("Propagated:\n");
2211  print_par_err(iP, DSLOT);
2212  printf("Updated:\n");
2213  print_par_err(iC, DSLOT);
2214 #endif
2215 
2216  // Fixup for failed propagation or invpt sign and charge.
2217  for (int i = 0; i < N_proc; ++i) {
2218  // PROP-FAIL-ENABLE The following to be enabled when propagation failure
2219  // detection is properly implemented in propagate-to-R/Z.
2220  // 1. The following code was only expecting barrel state to be restored.
2221  // auto barrel_pf(m_prop_config->backward_fit_pflags);
2222  // barrel_pf.copy_input_state_on_fail = true;
2223  // 2. There is also check on chi2, commented out to keep physics changes minimal.
2224  /*
2225  if (m_FailFlag[i] && LI.is_barrel()) {
2226  // Barrel pflags are set to include PF_copy_input_state_on_fail.
2227  // Endcap errors are immaterial here (relevant for fwd search), with prop error codes
2228  // one could do other things.
2229  // Are there also fail conditions in KalmanUpdate?
2230 #ifdef DEBUG
2231  if (debug && g_debug) {
2232  dprintf("MkFinder::bkFitFitTracks prop fail: chi2=%f, layer=%d, label=%d. Recovering.\n",
2233  tmp_chi2[i], LI.layer_id(), m_Label[i]);
2234  print_par_err(iC, i);
2235  }
2236 #endif
2237  m_Err[iC].copySlot(i, m_Err[iP]);
2238  m_Par[iC].copySlot(i, m_Par[iP]);
2239  } else if (tmp_chi2[i] > 200 || tmp_chi2[i] < 0) {
2240 #ifdef DEBUG
2241  if (debug && g_debug) {
2242  dprintf("MkFinder::bkFitFitTracks chi2 fail: chi2=%f, layer=%d, label=%d. Recovering.\n",
2243  tmp_chi2[i], LI.layer_id(), m_Label[i]);
2244  print_par_err(iC, i);
2245  }
2246 #endif
2247  // Go back to propagated state (at the current hit, the previous one is lost).
2248  m_Err[iC].copySlot(i, m_Err[iP]);
2249  m_Par[iC].copySlot(i, m_Par[iP]);
2250  }
2251  */
2252  // Fixup invpt sign and charge.
2253  if (m_Par[iC].At(i, 3, 0) < 0) {
2254  m_Chg.At(i, 0, 0) = -m_Chg.At(i, 0, 0);
2255  m_Par[iC].At(i, 3, 0) = -m_Par[iC].At(i, 3, 0);
2256  }
2257  }
2258 
2259 #if defined(DEBUG_BACKWARD_FIT)
2260  // clang-format off
2261  bool debug = true;
2262  const char beg_cur_sep = '/'; // set to ' ' root parsable printouts
2263  for (int i = 0; i < N_proc; ++i) {
2264  if (chiDebug && last_hit_ptr[i]) {
2265  TrackCand &bb = *m_TrkCand[i];
2266  int ti = iP;
2267  float chi = tmp_chi2.At(i, 0, 0);
2268  float chi_prnt = std::isfinite(chi) ? chi : -9;
2269 
2270 #if defined(MKFIT_STANDALONE)
2271  const MCHitInfo &mchi = m_event->simHitsInfo_[last_hit_ptr[i]->mcHitID()];
2272 
2273  dprintf("BKF_OVERLAP %d %d %d %d %d %d %d "
2274  "%f%c%f %f %f%c%f %f %f %f %d %d %d %d "
2275  "%f %f %f %f %f\n",
2276  m_event->evtID(),
2277 #else
2278  dprintf("BKF_OVERLAP %d %d %d %d %d %d "
2279  "%f%c%f %f %f%c%f %f %f %f %d %d %d "
2280  "%f %f %f %f %f\n",
2281 #endif
2282  bb.label(), (int)bb.prodType(), bb.isFindable(),
2283  layer, L.is_stereo(), L.is_barrel(),
2284  bb.pT(), beg_cur_sep, 1.0f / m_Par[ti].At(i, 3, 0),
2285  bb.posEta(),
2286  bb.posPhi(), beg_cur_sep, std::atan2(m_Par[ti].At(i, 1, 0), m_Par[ti].At(i, 0, 0)),
2287  std::hypot(m_Par[ti].At(i, 0, 0), m_Par[ti].At(i, 1, 0)),
2288  m_Par[ti].At(i, 2, 0),
2289  chi_prnt,
2290  std::isnan(chi), std::isfinite(chi), chi > 0,
2291 #if defined(MKFIT_STANDALONE)
2292  mchi.mcTrackID(),
2293 #endif
2294  // The following three can get negative / prouce nans in e2s.
2295  // std::abs the args for FPE hunt.
2296  e2s(std::abs(m_Err[ti].At(i, 0, 0))),
2297  e2s(std::abs(m_Err[ti].At(i, 1, 1))),
2298  e2s(std::abs(m_Err[ti].At(i, 2, 2))), // sx_t sy_t sz_t -- track errors
2299  1e4f * std::hypot(m_msPar.At(i, 0, 0) - m_Par[ti].At(i, 0, 0),
2300  m_msPar.At(i, 1, 0) - m_Par[ti].At(i, 1, 0)), // d_xy
2301  1e4f * (m_msPar.At(i, 2, 0) - m_Par[ti].At(i, 2, 0)) // d_z
2302  );
2303  }
2304  }
2305  // clang-format on
2306 #endif
2307 
2308  // update chi2
2309  m_Chi2.add(tmp_chi2);
2310  }
2311  }
2312 
2313  //------------------------------------------------------------------------------
2314 
2315  void MkFinder::bkFitPropTracksToPCA(const int N_proc) {
2317  }
2318 
2319 } // end namespace mkfit
float chi2_hit
Definition: Track.h:44
void(* m_compute_chi2_foo)(const MPlexLS &, const MPlexLV &, const MPlexQI &, const MPlexHS &, const MPlexHV &, MPlexQF &, MPlexLV &, MPlexQI &, const int, const PropagationFlags &, const bool)
Definition: FindingFoos.h:25
void setOriginIndex(int oi)
float getScoreCand(const track_score_func &score_func, const Track &cand1, bool penalizeTailMissHits=false, bool inFindCandidates=false)
Definition: Track.h:615
float x() const
Definition: Hit.h:162
void addHitIdx(int hitIdx, int hitLyr, float chi2)
def isnan(num)
MPlexQI m_Chg
Definition: MkBase.h:103
static constexpr int iC
Definition: MkBase.h:18
void copy_in(const Track &trk, const int mslot, const int tslot)
Definition: MkFinder.h:178
static constexpr int MPlexHitIdxMax
Definition: MkFinder.h:42
const SVector6 & parameters() const
Definition: Track.h:146
MPlex< T, D1, D2, N > hypot(const MPlex< T, D1, D2, N > &a, const MPlex< T, D1, D2, N > &b)
Definition: Matriplex.h:436
int charge() const
Definition: Track.h:185
MPlexQI m_NFoundHits
Definition: MkFinder.h:295
const IterationLayerConfig * m_iteration_layer_config
Definition: MkFinder.h:339
void chi2OfLoadedHit(int N_proc, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1784
Definition: APVGainStruct.h:7
const HitOnTrack * m_HoTArr[NN]
Definition: MkFinder.h:348
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
float rin() const
Definition: TrackerInfo.h:67
PropState ps_min
Definition: RntStructs.h:77
float q_bin() const
Definition: TrackerInfo.h:74
float good_frac() const
Definition: Event.h:55
void kalmanOperationEndcap(const int kfOp, const MPlexLS &psErr, const MPlexLV &psPar, const MPlexHS &msErr, const MPlexHV &msPar, MPlexLS &outErr, MPlexLV &outPar, MPlexQF &outChi2, const int N_proc)
void copy_out(Track &trk, const int mslot, const int tslot) const
Definition: MkFinder.h:195
void packModuleNormDir(const LayerOfHits &layer_of_hits, int hit_cnt, MPlexHV &norm, MPlexHV &dir, int N_proc) const
Definition: MkFinder.cc:240
void outputTracksAndHitIdx(std::vector< Track > &tracks, int beg, int end, bool outputProp) const
Definition: MkFinder.cc:217
const float chg[109]
Definition: CoreSimTrack.cc:5
float pT() const
Definition: Track.h:171
void propagateTracksToHitZ(const MPlexHV &par, const int N_proc, const PropagationFlags &pf, const MPlexQI *noMatEffPtr=nullptr)
Definition: MkBase.h:68
HitOnTrack m_HoTArrs[NN][Config::nMaxTrkHits]
Definition: MkFinder.h:297
bin_index_t qBinChecked(float q) const
Definition: HitStructures.h:73
const Hit * hitArray() const
void inputTracksAndHitIdx(const std::vector< Track > &tracks, int beg, int end, bool inputProp)
Definition: MkFinder.cc:99
void bkFitInputTracks(TrackVec &cands, int beg, int end)
Definition: MkFinder.cc:1829
const Event * m_event
Definition: MkFinder.h:342
for(int i=first, nt=offsets[nh];i< nt;i+=gridDim.x *blockDim.x)
Matriplex::Matriplex< float, HH, 1, NN > MPlexHV
Definition: Matrix.h:53
void setChi2(float chi2)
Definition: Track.h:191
Matriplex::Matriplex< unsigned short, 1, 1, NN > MPlexQUH
Definition: Matrix.h:75
Sin< T >::type sin(const T &t)
Definition: Sin.h:22
float chi2() const
Definition: Track.h:186
MPlexLV m_Par[2]
Definition: MkBase.h:102
PropagationFlags backward_fit_pflags
MPlexQI m_FailFlag
Definition: MkBase.h:104
ProdType prodType() const
Definition: Track.h:272
bool is_pixel() const
int label() const
Definition: Track.h:188
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 bkFitPropTracksToPCA(const int N_proc)
Definition: MkFinder.cc:2315
int evtID() const
Definition: Event.h:23
SMatrixSym66 & errors_nc()
Definition: Track.h:154
int mcTrackID() const
Definition: Hit.h:114
const IterationConfig * m_iteration_config
Definition: MkFinder.h:337
constexpr float PIOver2
Definition: Config.h:9
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
void release()
Definition: MkFinder.cc:56
void add_hit(const int mslot, int index, int layer)
Definition: MkFinder.h:247
Matriplex::Matriplex< float, LL, 1, NN > MPlexLV
Definition: Matrix.h:49
float getEta(float r, float z)
Definition: Hit.h:38
assert(be >=bs)
constexpr float TwoPI
Definition: Config.h:8
float exx() const
Definition: Hit.h:165
void swap(Association< C > &lhs, Association< C > &rhs)
Definition: Association.h:112
Definition: Electron.h:6
const float * posArray() const
Definition: Hit.h:151
static unsigned int maxChargePerCM()
Definition: Hit.h:234
float zmax() const
Definition: TrackerInfo.h:71
static constexpr int kHitStopIdx
Definition: Hit.h:194
const IterationParams * m_iteration_params
Definition: MkFinder.h:338
MPlexLS m_Err[2]
Definition: MkBase.h:101
void kalmanOperation(const int kfOp, const MPlexLS &psErr, const MPlexLV &psPar, const MPlexHS &msErr, const MPlexHV &msPar, MPlexLS &outErr, MPlexLV &outPar, MPlexQF &outChi2, const int N_proc)
void findCandidates(const LayerOfHits &layer_of_hits, std::vector< std::vector< TrackCand >> &tmp_candidates, const int offset, const int N_proc, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1253
static constexpr int kHitInGapIdx
Definition: Hit.h:197
const Double_t pi
track_score_func m_track_scorer
int m_current_region
Definition: MkFinder.h:343
float ezz() const
Definition: Hit.h:167
constexpr bool usePhiQArrays
Definition: Config.h:71
float momEta() const
Definition: Track.h:175
const HoTNode * hotsData() const
PropagationFlags finding_inter_layer_pflags
bool isStripQCompatible(int itrack, bool isBarrel, const MPlexLS &pErr, const MPlexLV &pPar, const MPlexHS &msErr, const MPlexHV &msPar)
Definition: MkFinder.cc:1185
void setScore(float s)
Definition: Track.h:192
float getScoreStruct(const track_score_func &score_func, const IdxChi2List &cand1)
Definition: Track.h:631
const PropagationConfig * m_prop_config
Definition: MkFinder.h:336
float zmin() const
Definition: TrackerInfo.h:70
float posR() const
Definition: Track.h:163
iterator make_iterator(IterationType_e type) const
unsigned int module
Definition: Track.h:37
int np
Definition: AMPTWrapper.h:43
int num_all_minus_one_hits(const int mslot) const
Definition: MkFinder.h:281
unsigned int detIDinLayer() const
Definition: Hit.h:228
bin_index_t phiBinChecked(float phi) const
Definition: HitStructures.h:77
const ModuleInfo & module_info(unsigned int sid) const
Definition: TrackerInfo.h:127
constexpr float PI
Definition: Config.h:7
void(* m_update_param_foo)(const MPlexLS &, const MPlexLV &, MPlexQI &, const MPlexHS &, const MPlexHV &, MPlexLS &, MPlexLV &, MPlexQI &, const int, const PropagationFlags &, const bool)
Definition: FindingFoos.h:26
Definition: EPCuts.h:4
tex
Definition: cuy.py:773
T sqrt(T t)
Definition: SSEVec.h:19
const float * errArray() const
Definition: Hit.h:152
constexpr Matriplex::idx_t NN
Definition: Matrix.h:43
unsigned int bin_content_t
Definition: HitStructures.h:27
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
PropState ps_max
Definition: RntStructs.h:77
int layer_id() const
Definition: TrackerInfo.h:65
float eyy() const
Definition: Hit.h:166
CombCandidate * combCandidate() const
Tan< T >::type tan(const T &t)
Definition: Tan.h:22
void kalmanPropagateAndUpdatePlane(const MPlexLS &psErr, const MPlexLV &psPar, MPlexQI &Chg, const MPlexHS &msErr, const MPlexHV &msPar, const MPlexHV &plNrm, const MPlexHV &plDir, MPlexLS &outErr, MPlexLV &outPar, MPlexQI &outFailFlag, const int N_proc, const PropagationFlags &propFlags, const bool propToHit)
MPlexQI m_XHitSize
Definition: MkFinder.h:322
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
MPlexHV m_msPar
Definition: MkFinder.h:327
void propagateTracksToHitR(const MPlexHV &par, const int N_proc, const PropagationFlags &pf, const MPlexQI *noMatEffPtr=nullptr)
Definition: MkBase.h:42
MPlexQI m_NTailMinusOneHits
Definition: MkFinder.h:312
double f[11][100]
bool isFindable() const
Definition: Track.h:265
void clearFailFlag()
Definition: MkBase.h:96
void min_max(const MPlex< T, D1, D2, N > &a, const MPlex< T, D1, D2, N > &b, MPlex< T, D1, D2, N > &min, MPlex< T, D1, D2, N > &max)
Definition: Matriplex.h:468
float ephi() const
Definition: Hit.h:172
const HitOnTrack * getHitsOnTrackArray() const
Definition: Track.h:507
MPlexQI m_SeedOriginIdx
Definition: MkFinder.h:301
int m_CurNode[NN]
Definition: MkFinder.h:349
MCHitInfoVec simHitsInfo_
Definition: Event.h:72
PropagationFlags pca_prop_pflags
float posEta() const
Definition: Track.h:166
constexpr float nSigmaPhi
BinSearch bso
Definition: RntStructs.h:78
float cdist(float a)
Definition: Config.h:32
int lastCcIndex() const
void begin_layer(const LayerOfHits &layer_of_hits)
Definition: MkFinder.cc:68
void kalmanPropagateAndComputeChi2Plane(const MPlexLS &psErr, const MPlexLV &psPar, const MPlexQI &inChg, const MPlexHS &msErr, const MPlexHV &msPar, const MPlexHV &plNrm, const MPlexHV &plDir, MPlexQF &outChi2, MPlexLV &propPar, MPlexQI &outFailFlag, const int N_proc, const PropagationFlags &propFlags, const bool propToHit)
MPlexHS m_msErr
Definition: MkFinder.h:326
void propagateTracksToPCAZ(const int N_proc, const PropagationFlags &pf)
Definition: MkBase.h:82
Matriplex::Matriplex< int, 1, 1, NN > MPlexQI
Definition: Matrix.h:72
ii
Definition: cuy.py:589
TrackVec simTracks_
Definition: Event.h:74
const LayerInfo * layer_info() const
TrackCand * m_TrkCand[NN]
Definition: MkFinder.h:318
void updateWithLoadedHit(int N_proc, const LayerOfHits &layer_of_hits, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1739
float y() const
Definition: Hit.h:163
void selectHitIndicesV2(const LayerOfHits &layer_of_hits, const int N_proc)
Definition: MkFinder.cc:751
std::vector< Track > TrackVec
SimLabelFromHits simLabelForCurrentSeed(int i) const
Definition: Event.cc:868
#define debug
Definition: HDRShower.cc:19
Matriplex::Matriplex< float, 1, 1, NN > MPlexQF
Definition: Matrix.h:71
WithinSensitiveRegion_e m_wsr
Definition: TrackerInfo.h:21
void pack(TMerr &err, TMpar &par)
void bkFitFitTracks(const EventOfHits &eventofhits, const SteeringParams &st_par, const int N_proc, bool chiDebug=false)
Definition: MkFinder.cc:2087
int m_CurHit[NN]
Definition: MkFinder.h:347
const SteeringParams * m_steering_params
Definition: MkFinder.h:340
static const FindingFoos & get_finding_foos(bool is_barrel)
Definition: FindingFoos.cc:18
float z() const
Definition: Track.h:162
std::vector< LayerControl > m_layer_plan
MPlexQI m_NOverlapHits
Definition: MkFinder.h:310
double b
Definition: hdecay.h:120
bool passStripChargePCMfromTrack(int itrack, bool isBarrel, unsigned int pcm, unsigned int pcmMin, const MPlexLV &pPar, const MPlexHS &msErr)
Definition: MkFinder.cc:1217
float getPhi(float x, float y)
Definition: Hit.h:34
float rout() const
Definition: TrackerInfo.h:68
const Track & currentSeed(int i) const
Definition: Event.cc:866
int nTotalHits() const
Definition: Track.h:526
MPlexHitIdx m_XHitArr
Definition: MkFinder.h:323
Matriplex::MatriplexSym< float, HH, NN > MPlexHS
Definition: Matrix.h:54
#define dprint(x)
Definition: Debug.h:95
MPlexQF m_Chi2
Definition: MkFinder.h:291
static constexpr int kHitMaxClusterIdx
Definition: Hit.h:196
void bkFitOutputTracks(TrackVec &cands, int beg, int end, bool outputProp)
Definition: MkFinder.cc:1886
void bkFitFitTracksBH(const EventOfHits &eventofhits, const SteeringParams &st_par, const int N_proc, bool chiDebug=false)
Definition: MkFinder.cc:1934
float z() const
Definition: Hit.h:164
const std::vector< float > & get_window_params(bool forward, bool fallback_to_other) const
MPlexQI m_CandIdx
Definition: MkFinder.h:300
double a
Definition: hdecay.h:121
MPlexQI m_SeedIdx
Definition: MkFinder.h:299
HitOnTrack hot(int i) const
void copyOutParErr(std::vector< CombCandidate > &seed_cand_vec, int N_proc, bool outputProp) const
Definition: MkFinder.cc:1808
int num_inside_minus_one_hits(const int mslot) const
Definition: MkFinder.h:285
void findCandidatesCloneEngine(const LayerOfHits &layer_of_hits, CandCloner &cloner, const int offset, const int N_proc, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1519
Matriplex::MatriplexSym< float, LL, NN > MPlexLS
Definition: Matrix.h:50
float x
const std::vector< bool > * m_iteration_hit_mask
Definition: MkFinder.h:341
bool is_barrel() const
PropagationFlags finding_intra_layer_pflags
int layer_id() const
void setCharge(int chg)
Definition: Track.h:190
BinSearch bsn
Definition: RntStructs.h:79
constexpr bool usePropToPlane
Definition: Config.h:51
void add_cand(int idx, const IdxChi2List &cand_info)
Definition: CandCloner.h:35
float getHitSelDynamicChi2Cut(const int itrk, const int ipar)
Definition: MkFinder.cc:293
MPF fast_atan2(const MPF &y, const MPF &x)
static constexpr int kHitMissIdx
Definition: Hit.h:193
const HoTNode * m_HoTNodeArr[NN]
Definition: MkFinder.h:350
unsigned short bin_index_t
Definition: HitStructures.h:26
float momPhi() const
Definition: Track.h:174
WSR_Result m_XWsrResult[NN]
Definition: MkFinder.h:321
float posPhi() const
Definition: Track.h:165
void getHitSelDynamicWindows(const float invpt, const float theta, float &min_dq, float &max_dq, float &min_dphi, float &max_dphi)
Definition: MkFinder.cc:262
Geom::Theta< T > theta() const
static constexpr int kHitEdgeIdx
Definition: Hit.h:195
CombCandidate & combCandWithOriginalIndex(int idx)
Definition: CandCloner.h:52
static unsigned int minChargePerCM()
Definition: Hit.h:233
SVector6 & parameters_nc()
Definition: Track.h:153
Power< A, B >::type pow(const A &a, const B &b)
Definition: Power.h:29
#define dprintf(...)
Definition: Debug.h:98
int mcHitID() const
Definition: Hit.h:187
MPlexQI m_Label
Definition: MkFinder.h:292
bool is_barrel() const
Definition: TrackerInfo.h:77
void end_layer()
Definition: MkFinder.cc:88
const Hit & refHit(int i) const
MPlex< T, D1, D2, N > sqrt(const MPlex< T, D1, D2, N > &a)
Definition: Matriplex.h:424
void print_par_err(int corp, int mslot) const
Definition: MkFinder.cc:2071
void addBestHit(const LayerOfHits &layer_of_hits, const int N_proc, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1041
constexpr bool isFinite(float x)