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 
10 //#define DEBUG
11 #include "Debug.h"
12 
13 #if (defined(DUMPHITWINDOW) || defined(DEBUG_BACKWARD_FIT)) && defined(MKFIT_STANDALONE)
15 #endif
16 
17 #include <algorithm>
18 
19 namespace mkfit {
20 
22  const IterationParams &ip,
23  const IterationLayerConfig &ilc,
24  const SteeringParams &sp,
25  const std::vector<bool> *ihm,
26  bool infwd) {
27  m_prop_config = &pc;
28  m_iteration_params = &ip;
30  m_steering_params = &sp;
32  m_in_fwd = infwd;
33  }
34 
36  m_prop_config = &pc;
37  m_steering_params = &sp;
38  }
39 
41  m_prop_config = nullptr;
42  m_iteration_params = nullptr;
43  m_iteration_layer_config = nullptr;
44  m_steering_params = nullptr;
45  m_iteration_hit_mask = nullptr;
46  m_in_fwd = true;
47  }
48 
49  //==============================================================================
50  // Input / Output TracksAndHitIdx
51  //==============================================================================
52 
53  void MkFinder::inputTracksAndHitIdx(const std::vector<Track> &tracks, int beg, int end, bool inputProp) {
54  // Assign track parameters to initial state and copy hit values in.
55 
56  // This might not be true for the last chunk!
57  // assert(end - beg == NN);
58 
59  const int iI = inputProp ? iP : iC;
60 
61  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
62  copy_in(tracks[i], imp, iI);
63  }
64  }
65 
67  const std::vector<Track> &tracks, const std::vector<int> &idxs, int beg, int end, bool inputProp, int mp_offset) {
68  // Assign track parameters to initial state and copy hit values in.
69 
70  // This might not be true for the last chunk!
71  // assert(end - beg == NN);
72 
73  const int iI = inputProp ? iP : iC;
74 
75  for (int i = beg, imp = mp_offset; i < end; ++i, ++imp) {
76  copy_in(tracks[idxs[i]], imp, iI);
77  }
78  }
79 
80  void MkFinder::inputTracksAndHitIdx(const std::vector<CombCandidate> &tracks,
81  const std::vector<std::pair<int, int>> &idxs,
82  int beg,
83  int end,
84  bool inputProp) {
85  // Assign track parameters to initial state and copy hit values in.
86 
87  // This might not be true for the last chunk!
88  // assert(end - beg == NN);
89 
90  const int iI = inputProp ? iP : iC;
91 
92  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
93  const TrackCand &trk = tracks[idxs[i].first][idxs[i].second];
94 
95  copy_in(trk, imp, iI);
96 
97 #ifdef DUMPHITWINDOW
98  m_SeedAlgo(imp, 0, 0) = tracks[idxs[i].first].seed_algo();
99  m_SeedLabel(imp, 0, 0) = tracks[idxs[i].first].seed_label();
100 #endif
101 
102  m_SeedIdx(imp, 0, 0) = idxs[i].first;
103  m_CandIdx(imp, 0, 0) = idxs[i].second;
104  }
105  }
106 
107  void MkFinder::inputTracksAndHits(const std::vector<CombCandidate> &tracks,
108  const LayerOfHits &layer_of_hits,
109  const std::vector<UpdateIndices> &idxs,
110  int beg,
111  int end,
112  bool inputProp) {
113  // Assign track parameters to initial state and copy hit values in.
114 
115  // This might not be true for the last chunk!
116  // assert(end - beg == NN);
117 
118  const int iI = inputProp ? iP : iC;
119 
120  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
121  const TrackCand &trk = tracks[idxs[i].seed_idx][idxs[i].cand_idx];
122 
123  copy_in(trk, imp, iI);
124 
125 #ifdef DUMPHITWINDOW
126  m_SeedAlgo(imp, 0, 0) = tracks[idxs[i].seed_idx].seed_algo();
127  m_SeedLabel(imp, 0, 0) = tracks[idxs[i].seed_idx.seed_label();
128 #endif
129 
130  m_SeedIdx(imp, 0, 0) = idxs[i].seed_idx;
131  m_CandIdx(imp, 0, 0) = idxs[i].cand_idx;
132 
133  const Hit &hit = layer_of_hits.refHit(idxs[i].hit_idx);
134  m_msErr.copyIn(imp, hit.errArray());
135  m_msPar.copyIn(imp, hit.posArray());
136  }
137  }
138 
139  void MkFinder::inputTracksAndHitIdx(const std::vector<CombCandidate> &tracks,
140  const std::vector<std::pair<int, IdxChi2List>> &idxs,
141  int beg,
142  int end,
143  bool inputProp) {
144  // Assign track parameters to initial state and copy hit values in.
145 
146  // This might not be true for the last chunk!
147  // assert(end - beg == NN);
148 
149  const int iI = inputProp ? iP : iC;
150 
151  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
152  const TrackCand &trk = tracks[idxs[i].first][idxs[i].second.trkIdx];
153 
154  copy_in(trk, imp, iI);
155 
156 #ifdef DUMPHITWINDOW
157  m_SeedAlgo(imp, 0, 0) = tracks[idxs[i].first].seed_algo();
158  m_SeedLabel(imp, 0, 0) = tracks[idxs[i].first].seed_label();
159 #endif
160 
161  m_SeedIdx(imp, 0, 0) = idxs[i].first;
162  m_CandIdx(imp, 0, 0) = idxs[i].second.trkIdx;
163  }
164  }
165 
166  void MkFinder::outputTracksAndHitIdx(std::vector<Track> &tracks, int beg, int end, bool outputProp) const {
167  // Copies requested track parameters into Track objects.
168  // The tracks vector should be resized to allow direct copying.
169 
170  const int iO = outputProp ? iP : iC;
171 
172  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
173  copy_out(tracks[i], imp, iO);
174  }
175  }
176 
178  std::vector<Track> &tracks, const std::vector<int> &idxs, int beg, int end, bool outputProp) const {
179  // Copies requested track parameters into Track objects.
180  // The tracks vector should be resized to allow direct copying.
181 
182  const int iO = outputProp ? iP : iC;
183 
184  for (int i = beg, imp = 0; i < end; ++i, ++imp) {
185  copy_out(tracks[idxs[i]], imp, iO);
186  }
187  }
188 
189  //==============================================================================
190  // getHitSelDynamicWindows
191  //==============================================================================
192  // From HitSelectionWindows.h: track-related config on hit selection windows
193 
195  const float invpt, const float theta, float &min_dq, float &max_dq, float &min_dphi, float &max_dphi) {
196  float max_invpt = std::min(invpt, 10.0f); // => pT>0.1 GeV
197 
198  enum SelWinParameters_e { dp_sf = 0, dp_0, dp_1, dp_2, dq_sf, dq_0, dq_1, dq_2 };
200 
201  if (!v.empty()) {
202  // dq hit selection window
203  float this_dq = v[dq_sf] * (v[dq_0] * max_invpt + v[dq_1] * theta + v[dq_2]);
204  // In case value is below 0 (bad window derivation or other reasons), leave original limits
205  if (this_dq > 0.f) {
206  min_dq = this_dq;
207  max_dq = 2.0f * min_dq;
208  }
209 
210  // dphi hit selection window
211  float this_dphi = v[dp_sf] * (v[dp_0] * max_invpt + v[dp_1] * theta + v[dp_2]);
212  // In case value is too low (bad window derivation or other reasons), leave original limits
213  if (this_dphi > min_dphi) {
214  min_dphi = this_dphi;
215  max_dphi = 2.0f * min_dphi;
216  }
217  }
218  }
219 
220  //==============================================================================
221  // getHitSelDynamicChi2Cut
222  //==============================================================================
223  // From HitSelectionWindows.h: track-related config on hit selection windows
224 
225  inline float MkFinder::getHitSelDynamicChi2Cut(const int itrk, const int ipar) {
226  const float minChi2Cut = m_iteration_params->chi2Cut_min;
227  const float invpt = m_Par[ipar].At(itrk, 3, 0);
228  const float theta = std::abs(m_Par[ipar].At(itrk, 5, 0) - Const::PIOver2);
229 
230  float max_invpt = std::min(invpt, 10.0f); // => pT>0.1 GeV
231 
232  enum SelWinParameters_e { c2_sf = 8, c2_0, c2_1, c2_2 };
234 
235  if (!v.empty()) {
236  float this_c2 = v[c2_sf] * (v[c2_0] * max_invpt + v[c2_1] * theta + v[c2_2]);
237  // In case value is too low (bad window derivation or other reasons), leave original limits
238  if (this_c2 > minChi2Cut)
239  return this_c2;
240  }
241  return minChi2Cut;
242  }
243 
244  //==============================================================================
245  // SelectHitIndices
246  //==============================================================================
247 
248  void MkFinder::selectHitIndices(const LayerOfHits &layer_of_hits, const int N_proc) {
249  // bool debug = true;
250  using bidx_t = LayerOfHits::bin_index_t;
251  using bcnt_t = LayerOfHits::bin_content_t;
252  const LayerOfHits &L = layer_of_hits;
254 
255  const int iI = iP;
256  const float nSigmaPhi = 3;
257  const float nSigmaZ = 3;
258  const float nSigmaR = 3;
259 
260  dprintf("LayerOfHits::SelectHitIndices %s layer=%d N_proc=%d\n",
261  L.is_barrel() ? "barrel" : "endcap",
262  L.layer_id(),
263  N_proc);
264 
265  float dqv[NN], dphiv[NN], qv[NN], phiv[NN];
266  bidx_t qb1v[NN], qb2v[NN], qbv[NN], pb1v[NN], pb2v[NN];
267 
268  const auto assignbins = [&](int itrack,
269  float q,
270  float dq,
271  float phi,
272  float dphi,
273  float min_dq,
274  float max_dq,
275  float min_dphi,
276  float max_dphi) {
277  dphi = std::clamp(std::abs(dphi), min_dphi, max_dphi);
278  dq = std::clamp(dq, min_dq, max_dq);
279  //
280  qv[itrack] = q;
281  phiv[itrack] = phi;
282  dphiv[itrack] = dphi;
283  dqv[itrack] = dq;
284  //
285  qbv[itrack] = L.qBinChecked(q);
286  qb1v[itrack] = L.qBinChecked(q - dq);
287  qb2v[itrack] = L.qBinChecked(q + dq) + 1;
288  pb1v[itrack] = L.phiBinChecked(phi - dphi);
289  pb2v[itrack] = L.phiMaskApply(L.phiBin(phi + dphi) + 1);
290  };
291 
292  const auto calcdphi2 = [&](int itrack, float dphidx, float dphidy) {
293  return dphidx * dphidx * m_Err[iI].constAt(itrack, 0, 0) + dphidy * dphidy * m_Err[iI].constAt(itrack, 1, 1) +
294  2 * dphidx * dphidy * m_Err[iI].constAt(itrack, 0, 1);
295  };
296 
297  const auto calcdphi = [&](float dphi2, float min_dphi) {
298  return std::max(nSigmaPhi * std::sqrt(std::abs(dphi2)), min_dphi);
299  };
300 
301  if (L.is_barrel()) {
302  // Pull out the part of the loop that vectorizes
303 #pragma omp simd
304  for (int itrack = 0; itrack < NN; ++itrack) {
305  m_XHitSize[itrack] = 0;
306 
307  float min_dq = ILC.min_dq();
308  float max_dq = ILC.max_dq();
309  float min_dphi = ILC.min_dphi();
310  float max_dphi = ILC.max_dphi();
311 
312  const float invpt = m_Par[iI].At(itrack, 3, 0);
313  const float theta = std::fabs(m_Par[iI].At(itrack, 5, 0) - Const::PIOver2);
314  getHitSelDynamicWindows(invpt, theta, min_dq, max_dq, min_dphi, max_dphi);
315 
316  const float x = m_Par[iI].constAt(itrack, 0, 0);
317  const float y = m_Par[iI].constAt(itrack, 1, 0);
318  const float r2 = x * x + y * y;
319  const float dphidx = -y / r2, dphidy = x / r2;
320  const float dphi2 = calcdphi2(itrack, dphidx, dphidy);
321 #ifdef HARD_CHECK
322  assert(dphi2 >= 0);
323 #endif
324 
325  const float phi = getPhi(x, y);
326  float dphi = calcdphi(dphi2, min_dphi);
327 
328  const float z = m_Par[iI].constAt(itrack, 2, 0);
329  const float dz = std::abs(nSigmaZ * std::sqrt(m_Err[iI].constAt(itrack, 2, 2)));
330  const float edgeCorr = std::abs(0.5f * (L.layer_info()->rout() - L.layer_info()->rin()) /
331  std::tan(m_Par[iI].constAt(itrack, 5, 0)));
332  // XXX-NUM-ERR above, m_Err(2,2) gets negative!
333 
334  m_XWsrResult[itrack] = L.is_within_z_sensitive_region(z, std::sqrt(dz * dz + edgeCorr * edgeCorr));
335  assignbins(itrack, z, dz, phi, dphi, min_dq, max_dq, min_dphi, max_dphi);
336  }
337  } else // endcap
338  {
339  //layer half-thikness for dphi spread calculation; only for very restrictive iters
340  const float layerD = std::abs(L.layer_info()->zmax() - L.layer_info()->zmin()) * 0.5f *
342  // Pull out the part of the loop that vectorizes
343 #pragma omp simd
344  for (int itrack = 0; itrack < NN; ++itrack) {
345  m_XHitSize[itrack] = 0;
346 
347  float min_dq = ILC.min_dq();
348  float max_dq = ILC.max_dq();
349  float min_dphi = ILC.min_dphi();
350  float max_dphi = ILC.max_dphi();
351 
352  const float invpt = m_Par[iI].At(itrack, 3, 0);
353  const float theta = std::fabs(m_Par[iI].At(itrack, 5, 0) - Const::PIOver2);
354  getHitSelDynamicWindows(invpt, theta, min_dq, max_dq, min_dphi, max_dphi);
355 
356  const float x = m_Par[iI].constAt(itrack, 0, 0);
357  const float y = m_Par[iI].constAt(itrack, 1, 0);
358  const float r2 = x * x + y * y;
359  const float r2Inv = 1.f / r2;
360  const float dphidx = -y * r2Inv, dphidy = x * r2Inv;
361  const float phi = getPhi(x, y);
362  const float dphi2 =
363  calcdphi2(itrack, dphidx, dphidy)
364  //range from finite layer thickness
365  + std::pow(layerD * std::tan(m_Par[iI].At(itrack, 5, 0)) * std::sin(m_Par[iI].At(itrack, 4, 0) - phi), 2) *
366  r2Inv;
367 #ifdef HARD_CHECK
368  assert(dphi2 >= 0);
369 #endif
370 
371  float dphi = calcdphi(dphi2, min_dphi);
372 
373  const float r = std::sqrt(r2);
374  const float dr = nSigmaR * std::sqrt(std::abs(x * x * m_Err[iI].constAt(itrack, 0, 0) +
375  y * y * m_Err[iI].constAt(itrack, 1, 1) +
376  2 * x * y * m_Err[iI].constAt(itrack, 0, 1)) /
377  r2);
378  const float edgeCorr = std::abs(0.5f * (L.layer_info()->zmax() - L.layer_info()->zmin()) *
379  std::tan(m_Par[iI].constAt(itrack, 5, 0)));
380 
381  m_XWsrResult[itrack] = L.is_within_r_sensitive_region(r, std::sqrt(dr * dr + edgeCorr * edgeCorr));
382  assignbins(itrack, r, dr, phi, dphi, min_dq, max_dq, min_dphi, max_dphi);
383  }
384  }
385 
386  // Vectorizing this makes it run slower!
387  //#pragma omp simd
388  for (int itrack = 0; itrack < N_proc; ++itrack) {
389  // PROP-FAIL-ENABLE The following to be enabled when propagation failure
390  // detection is properly implemented in propagate-to-R/Z.
391  // if (m_FailFlag[itrack]) {
392  // m_XWsrResult[itrack].m_wsr = WSR_Failed;
393  // m_XHitSize[itrack] = -1;
394  // continue;
395  // }
396 
397  if (m_XWsrResult[itrack].m_wsr == WSR_Outside) {
398  m_XHitSize[itrack] = -1;
399  continue;
400  }
401 
402  const bidx_t qb = qbv[itrack];
403  const bidx_t qb1 = qb1v[itrack];
404  const bidx_t qb2 = qb2v[itrack];
405  const bidx_t pb1 = pb1v[itrack];
406  const bidx_t pb2 = pb2v[itrack];
407 
408  // Used only by usePhiQArrays
409  const float q = qv[itrack];
410  const float phi = phiv[itrack];
411  const float dphi = dphiv[itrack];
412  const float dq = dqv[itrack];
413  // clang-format off
414  dprintf(" %2d/%2d: %6.3f %6.3f %6.6f %7.5f %3u %3u %4u %4u\n",
415  L.layer_id(), itrack, q, phi, dq, dphi,
416  qb1, qb2, pb1, pb2);
417  // clang-format on
418  // MT: One could iterate in "spiral" order, to pick hits close to the center.
419  // http://stackoverflow.com/questions/398299/looping-in-a-spiral
420  // This would then work best with relatively small bin sizes.
421  // Or, set them up so I can always take 3x3 array around the intersection.
422 
423 #if defined(DUMPHITWINDOW) && defined(MKFIT_STANDALONE)
424  int thisseedmcid = -999999;
425  {
426  int seedlabel = m_SeedLabel(itrack, 0, 0);
427  TrackVec &seedtracks = m_event->seedTracks_;
428  int thisidx = -999999;
429  for (int i = 0; i < int(seedtracks.size()); ++i) {
430  auto &thisseed = seedtracks[i];
431  if (thisseed.label() == seedlabel) {
432  thisidx = i;
433  break;
434  }
435  }
436  if (thisidx > -999999) {
437  auto &seedtrack = m_event->seedTracks_[thisidx];
438  std::vector<int> thismcHitIDs;
439  seedtrack.mcHitIDsVec(m_event->layerHits_, m_event->simHitsInfo_, thismcHitIDs);
440  if (std::adjacent_find(thismcHitIDs.begin(), thismcHitIDs.end(), std::not_equal_to<>()) ==
441  thismcHitIDs.end()) {
442  thisseedmcid = thismcHitIDs.at(0);
443  }
444  }
445  }
446 #endif
447 
448  for (bidx_t qi = qb1; qi != qb2; ++qi) {
449  for (bidx_t pi = pb1; pi != pb2; pi = L.phiMaskApply(pi + 1)) {
450  // Limit to central Q-bin
451  if (qi == qb && L.isBinDead(pi, qi) == true) {
452  dprint("dead module for track in layer=" << L.layer_id() << " qb=" << qi << " pi=" << pi << " q=" << q
453  << " phi=" << phi);
454  m_XWsrResult[itrack].m_in_gap = true;
455  }
456 
457  // MT: The following line is the biggest hog (4% total run time).
458  // This comes from cache misses, I presume.
459  // It might make sense to make first loop to extract bin indices
460  // and issue prefetches at the same time.
461  // Then enter vectorized loop to actually collect the hits in proper order.
462 
463  //SK: ~20x1024 bin sizes give mostly 1 hit per bin. Commented out for 128 bins or less
464  // #pragma nounroll
465  auto pbi = L.phiQBinContent(pi, qi);
466  for (bcnt_t hi = pbi.begin(); hi < pbi.end(); ++hi) {
467  // MT: Access into m_hit_zs and m_hit_phis is 1% run-time each.
468 
469  unsigned int hi_orig = L.getOriginalHitIndex(hi);
470 
471  if (m_iteration_hit_mask && (*m_iteration_hit_mask)[hi_orig]) {
472  dprintf(
473  "Yay, denying masked hit on layer %u, hi %u, orig idx %u\n", L.layer_info()->layer_id(), hi, hi_orig);
474  continue;
475  }
476 
477  if (Config::usePhiQArrays) {
478  if (m_XHitSize[itrack] >= MPlexHitIdxMax)
479  break;
480 
481  const float ddq = std::abs(q - L.hit_q(hi));
482  const float ddphi = cdist(std::abs(phi - L.hit_phi(hi)));
483 
484 #if defined(DUMPHITWINDOW) && defined(MKFIT_STANDALONE)
485  {
486  const MCHitInfo &mchinfo = m_event->simHitsInfo_[L.refHit(hi).mcHitID()];
487  int mchid = mchinfo.mcTrackID();
488  int st_isfindable = 0;
489  int st_label = -999999;
490  int st_prodtype = 0;
491  int st_nhits = -1;
492  int st_charge = 0;
493  float st_r = -999.;
494  float st_z = -999.;
495  float st_pt = -999.;
496  float st_eta = -999.;
497  float st_phi = -999.;
498  if (mchid >= 0) {
499  Track simtrack = m_event->simTracks_[mchid];
500  st_isfindable = (int)simtrack.isFindable();
501  st_label = simtrack.label();
502  st_prodtype = (int)simtrack.prodType();
503  st_pt = simtrack.pT();
504  st_eta = simtrack.momEta();
505  st_phi = simtrack.momPhi();
506  st_nhits = simtrack.nTotalHits();
507  st_charge = simtrack.charge();
508  st_r = simtrack.posR();
509  st_z = simtrack.z();
510  }
511 
512  const Hit &thishit = L.refHit(hi);
513  m_msErr.copyIn(itrack, thishit.errArray());
514  m_msPar.copyIn(itrack, thishit.posArray());
515 
516  MPlexQF thisOutChi2;
517  MPlexLV tmpPropPar;
518  const FindingFoos &fnd_foos = FindingFoos::get_finding_foos(L.is_barrel());
519  (*fnd_foos.m_compute_chi2_foo)(m_Err[iI],
520  m_Par[iI],
521  m_Chg,
522  m_msErr,
523  m_msPar,
524  thisOutChi2,
525  tmpPropPar,
526  N_proc,
529 
530  float hx = thishit.x();
531  float hy = thishit.y();
532  float hz = thishit.z();
533  float hr = std::hypot(hx, hy);
534  float hphi = std::atan2(hy, hx);
535  float hex = std::sqrt(thishit.exx());
536  if (std::isnan(hex))
537  hex = -999.;
538  float hey = std::sqrt(thishit.eyy());
539  if (std::isnan(hey))
540  hey = -999.;
541  float hez = std::sqrt(thishit.ezz());
542  if (std::isnan(hez))
543  hez = -999.;
544  float her = std::sqrt(
545  (hx * hx * thishit.exx() + hy * hy * thishit.eyy() + 2.0f * hx * hy * m_msErr.At(itrack, 0, 1)) /
546  (hr * hr));
547  if (std::isnan(her))
548  her = -999.;
549  float hephi = std::sqrt(thishit.ephi());
550  if (std::isnan(hephi))
551  hephi = -999.;
552  float hchi2 = thisOutChi2[itrack];
553  if (std::isnan(hchi2))
554  hchi2 = -999.;
555  float tx = m_Par[iI].At(itrack, 0, 0);
556  float ty = m_Par[iI].At(itrack, 1, 0);
557  float tz = m_Par[iI].At(itrack, 2, 0);
558  float tr = std::hypot(tx, ty);
559  float tphi = std::atan2(ty, tx);
560  float tchi2 = m_Chi2(itrack, 0, 0);
561  if (std::isnan(tchi2))
562  tchi2 = -999.;
563  float tex = std::sqrt(m_Err[iI].At(itrack, 0, 0));
564  if (std::isnan(tex))
565  tex = -999.;
566  float tey = std::sqrt(m_Err[iI].At(itrack, 1, 1));
567  if (std::isnan(tey))
568  tey = -999.;
569  float tez = std::sqrt(m_Err[iI].At(itrack, 2, 2));
570  if (std::isnan(tez))
571  tez = -999.;
572  float ter = std::sqrt(
573  (tx * tx * tex * tex + ty * ty * tey * tey + 2.0f * tx * ty * m_Err[iI].At(itrack, 0, 1)) /
574  (tr * tr));
575  if (std::isnan(ter))
576  ter = -999.;
577  float tephi = std::sqrt(
578  (ty * ty * tex * tex + tx * tx * tey * tey - 2.0f * tx * ty * m_Err[iI].At(itrack, 0, 1)) /
579  (tr * tr * tr * tr));
580  if (std::isnan(tephi))
581  tephi = -999.;
582  float ht_dxy = std::hypot(hx - tx, hy - ty);
583  float ht_dz = hz - tz;
584  float ht_dphi = cdist(std::abs(hphi - tphi));
585 
586  static bool first = true;
587  if (first) {
588  printf(
589  "HITWINDOWSEL "
590  "evt_id/I:"
591  "lyr_id/I:lyr_isbrl/I:hit_idx/I:"
592  "trk_cnt/I:trk_idx/I:trk_label/I:"
593  "trk_pt/F:trk_eta/F:trk_mphi/F:trk_chi2/F:"
594  "nhits/I:"
595  "seed_idx/I:seed_label/I:seed_algo/I:seed_mcid/I:"
596  "hit_mcid/I:"
597  "st_isfindable/I:st_prodtype/I:st_label/I:"
598  "st_pt/F:st_eta/F:st_phi/F:"
599  "st_nhits/I:st_charge/I:st_r/F:st_z/F:"
600  "trk_q/F:hit_q/F:dq_trkhit/F:dq_cut/F:trk_phi/F:hit_phi/F:dphi_trkhit/F:dphi_cut/F:"
601  "t_x/F:t_y/F:t_r/F:t_phi/F:t_z/F:"
602  "t_ex/F:t_ey/F:t_er/F:t_ephi/F:t_ez/F:"
603  "h_x/F:h_y/F:h_r/F:h_phi/F:h_z/F:"
604  "h_ex/F:h_ey/F:h_er/F:h_ephi/F:h_ez/F:"
605  "ht_dxy/F:ht_dz/F:ht_dphi/F:"
606  "h_chi2/F"
607  "\n");
608  first = false;
609  }
610 
611  if (!(std::isnan(phi)) && !(std::isnan(getEta(m_Par[iI].At(itrack, 5, 0))))) {
612  //|| std::isnan(ter) || std::isnan(her) || std::isnan(m_Chi2(itrack, 0, 0)) || std::isnan(hchi2)))
613  // clang-format off
614  printf("HITWINDOWSEL "
615  "%d "
616  "%d %d %d "
617  "%d %d %d "
618  "%6.3f %6.3f %6.3f %6.3f "
619  "%d "
620  "%d %d %d %d "
621  "%d "
622  "%d %d %d "
623  "%6.3f %6.3f %6.3f "
624  "%d %d %6.3f %6.3f "
625  "%6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f %6.3f "
626  "%6.3f %6.3f %6.3f %6.3f %6.3f "
627  "%6.6f %6.6f %6.6f %6.6f %6.6f "
628  "%6.3f %6.3f %6.3f %6.3f %6.3f "
629  "%6.6f %6.6f %6.6f %6.6f %6.6f "
630  "%6.3f %6.3f %6.3f "
631  "%6.3f"
632  "\n",
633  m_event->evtID(),
634  L.layer_id(), L.is_barrel(), L.getOriginalHitIndex(hi),
635  itrack, m_CandIdx(itrack, 0, 0), m_Label(itrack, 0, 0),
636  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),
637  m_NFoundHits(itrack, 0, 0),
638  m_SeedIdx(itrack, 0, 0), m_SeedLabel(itrack, 0, 0), m_SeedAlgo(itrack, 0, 0), thisseedmcid,
639  mchid,
640  st_isfindable, st_prodtype, st_label,
641  st_pt, st_eta, st_phi,
642  st_nhits, st_charge, st_r, st_z,
643  q, L.hit_q(hi), ddq, dq, phi, L.hit_phi(hi), ddphi, dphi,
644  tx, ty, tr, tphi, tz,
645  tex, tey, ter, tephi, tez,
646  hx, hy, hr, hphi, hz,
647  hex, hey, her, hephi, hez,
648  ht_dxy, ht_dz, ht_dphi,
649  hchi2);
650  // clang-format on
651  }
652  }
653 #endif
654 
655  if (ddq >= dq)
656  continue;
657  if (ddphi >= dphi)
658  continue;
659  // clang-format off
660  dprintf(" SHI %3u %4u %5u %6.3f %6.3f %6.4f %7.5f %s\n",
661  qi, pi, hi, L.hit_q(hi), L.hit_phi(hi),
662  ddq, ddphi, (ddq < dq && ddphi < dphi) ? "PASS" : "FAIL");
663  // clang-format on
664 
665  // MT: Removing extra check gives full efficiency ...
666  // and means our error estimations are wrong!
667  // Avi says we should have *minimal* search windows per layer.
668  // Also ... if bins are sufficiently small, we do not need the extra
669  // checks, see above.
670  m_XHitArr.At(itrack, m_XHitSize[itrack]++, 0) = hi_orig;
671  } else {
672  // MT: The following check alone makes more sense with spiral traversal,
673  // we'd be taking in closest hits first.
674 
675  // Hmmh -- there used to be some more checks here.
676  // Or, at least, the phi binning was much smaller and no further checks were done.
677  assert(false && "this code has not been used in a while -- see comments in code");
678 
679  if (m_XHitSize[itrack] < MPlexHitIdxMax) {
680  m_XHitArr.At(itrack, m_XHitSize[itrack]++, 0) = hi_orig;
681  }
682  }
683  } //hi
684  } //pi
685  } //qi
686  } //itrack
687  }
688 
689  //==============================================================================
690  // AddBestHit - Best Hit Track Finding
691  //==============================================================================
692 
693  void MkFinder::addBestHit(const LayerOfHits &layer_of_hits, const int N_proc, const FindingFoos &fnd_foos) {
694  // debug = true;
695 
696  MatriplexHitPacker mhp(layer_of_hits.hitArray());
697 
698  float minChi2[NN];
699  int bestHit[NN];
700  int maxSize = 0;
701 
702  // Determine maximum number of hits for tracks in the collection.
703  for (int it = 0; it < NN; ++it) {
704  if (it < N_proc) {
705  if (m_XHitSize[it] > 0) {
707  }
708  }
709 
710  bestHit[it] = -1;
712  }
713 
714  for (int hit_cnt = 0; hit_cnt < maxSize; ++hit_cnt) {
715  //fixme what if size is zero???
716 
717  mhp.reset();
718 
719 #pragma omp simd
720  for (int itrack = 0; itrack < N_proc; ++itrack) {
721  if (hit_cnt < m_XHitSize[itrack]) {
722  mhp.addInputAt(itrack, layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0)));
723  }
724  }
725 
726  mhp.pack(m_msErr, m_msPar);
727 
728  //now compute the chi2 of track state vs hit
729  MPlexQF outChi2;
730  MPlexLV tmpPropPar;
731  clearFailFlag();
732  (*fnd_foos.m_compute_chi2_foo)(m_Err[iP],
733  m_Par[iP],
734  m_Chg,
735  m_msErr,
736  m_msPar,
737  outChi2,
738  tmpPropPar,
739  m_FailFlag,
740  N_proc,
743 
744  //update best hit in case chi2<minChi2
745 #pragma omp simd
746  for (int itrack = 0; itrack < N_proc; ++itrack) {
747  if (hit_cnt < m_XHitSize[itrack]) {
748  const float chi2 = std::abs(outChi2[itrack]); //fixme negative chi2 sometimes...
749  dprint("chi2=" << chi2 << " minChi2[itrack]=" << minChi2[itrack]);
750  if (chi2 < minChi2[itrack]) {
751  minChi2[itrack] = chi2;
752  bestHit[itrack] = m_XHitArr.At(itrack, hit_cnt, 0);
753  }
754  }
755  }
756  } // end loop over hits
757 
758  //#pragma omp simd
759  for (int itrack = 0; itrack < N_proc; ++itrack) {
760  if (m_XWsrResult[itrack].m_wsr == WSR_Outside) {
761  // Why am I doing this?
762  m_msErr.setDiagonal3x3(itrack, 666);
763  m_msPar(itrack, 0, 0) = m_Par[iP](itrack, 0, 0);
764  m_msPar(itrack, 1, 0) = m_Par[iP](itrack, 1, 0);
765  m_msPar(itrack, 2, 0) = m_Par[iP](itrack, 2, 0);
766 
767  // XXXX If not in gap, should get back the old track params. But they are gone ...
768  // Would actually have to do it right after SelectHitIndices where updated params are still ok.
769  // Here they got screwed during hit matching.
770  // So, I'd store them there (into propagated params) and retrieve them here.
771  // Or we decide not to care ...
772 
773  continue;
774  }
775 
776  //fixme decide what to do in case no hit found
777  if (bestHit[itrack] >= 0) {
778  const Hit &hit = layer_of_hits.refHit(bestHit[itrack]);
779  const float chi2 = minChi2[itrack];
780 
781  dprint("ADD BEST HIT FOR TRACK #"
782  << itrack << std::endl
783  << "prop x=" << m_Par[iP].constAt(itrack, 0, 0) << " y=" << m_Par[iP].constAt(itrack, 1, 0) << std::endl
784  << "copy in hit #" << bestHit[itrack] << " x=" << hit.position()[0] << " y=" << hit.position()[1]);
785 
786  m_msErr.copyIn(itrack, hit.errArray());
787  m_msPar.copyIn(itrack, hit.posArray());
788  m_Chi2(itrack, 0, 0) += chi2;
789 
790  add_hit(itrack, bestHit[itrack], layer_of_hits.layer_id());
791  } else {
792  int fake_hit_idx = Hit::kHitMissIdx;
793 
794  if (m_XWsrResult[itrack].m_wsr == WSR_Edge) {
795  // YYYYYY Config::store_missed_layers
796  fake_hit_idx = Hit::kHitEdgeIdx;
797  } else if (num_all_minus_one_hits(itrack)) {
798  fake_hit_idx = Hit::kHitStopIdx;
799  }
800 
801  dprint("ADD FAKE HIT FOR TRACK #" << itrack << " withinBounds=" << (fake_hit_idx != Hit::kHitEdgeIdx)
802  << " r=" << std::hypot(m_Par[iP](itrack, 0, 0), m_Par[iP](itrack, 1, 0)));
803 
804  m_msErr.setDiagonal3x3(itrack, 666);
805  m_msPar(itrack, 0, 0) = m_Par[iP](itrack, 0, 0);
806  m_msPar(itrack, 1, 0) = m_Par[iP](itrack, 1, 0);
807  m_msPar(itrack, 2, 0) = m_Par[iP](itrack, 2, 0);
808  // Don't update chi2
809 
810  add_hit(itrack, fake_hit_idx, layer_of_hits.layer_id());
811  }
812  }
813 
814  // Update the track parameters with this hit. (Note that some calculations
815  // are already done when computing chi2. Not sure it's worth caching them?)
816 
817  dprint("update parameters");
818  clearFailFlag();
819  (*fnd_foos.m_update_param_foo)(m_Err[iP],
820  m_Par[iP],
821  m_Chg,
822  m_msErr,
823  m_msPar,
824  m_Err[iC],
825  m_Par[iC],
826  m_FailFlag,
827  N_proc,
830 
831  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));
832  }
833 
834  //=======================================================
835  // isStripQCompatible : check if prop is consistent with the barrel/endcap strip length
836  //=======================================================
838  int itrack, bool isBarrel, const MPlexLS &pErr, const MPlexLV &pPar, const MPlexHS &msErr, const MPlexHV &msPar) {
839  //check module compatibility via long strip side = L/sqrt(12)
840  if (isBarrel) { //check z direction only
841  const float res = std::abs(msPar.constAt(itrack, 2, 0) - pPar.constAt(itrack, 2, 0));
842  const float hitHL = sqrt(msErr.constAt(itrack, 2, 2) * 3.f); //half-length
843  const float qErr = sqrt(pErr.constAt(itrack, 2, 2));
844  dprint("qCompat " << hitHL << " + " << 3.f * qErr << " vs " << res);
845  return hitHL + std::max(3.f * qErr, 0.5f) > res;
846  } else { //project on xy, assuming the strip Length >> Width
847  const float res[2]{msPar.constAt(itrack, 0, 0) - pPar.constAt(itrack, 0, 0),
848  msPar.constAt(itrack, 1, 0) - pPar.constAt(itrack, 1, 0)};
849  const float hitT2 = msErr.constAt(itrack, 0, 0) + msErr.constAt(itrack, 1, 1);
850  const float hitT2inv = 1.f / hitT2;
851  const float proj[3] = {msErr.constAt(itrack, 0, 0) * hitT2inv,
852  msErr.constAt(itrack, 0, 1) * hitT2inv,
853  msErr.constAt(itrack, 1, 1) * hitT2inv};
854  const float qErr =
855  sqrt(std::abs(pErr.constAt(itrack, 0, 0) * proj[0] + 2.f * pErr.constAt(itrack, 0, 1) * proj[1] +
856  pErr.constAt(itrack, 1, 1) * proj[2])); //take abs to avoid non-pos-def cases
857  const float resProj =
858  sqrt(res[0] * proj[0] * res[0] + 2.f * res[1] * proj[1] * res[0] + res[1] * proj[2] * res[1]);
859  dprint("qCompat " << sqrt(hitT2 * 3.f) << " + " << 3.f * qErr << " vs " << resProj);
860  return sqrt(hitT2 * 3.f) + std::max(3.f * qErr, 0.5f) > resProj;
861  }
862  }
863 
864  //=======================================================
865  // passStripChargePCMfromTrack : apply the slope correction to charge per cm and cut using hit err matrix
866  // the raw pcm = charge/L_normal
867  // the corrected qCorr = charge/L_path = charge/(L_normal*p/p_zLocal) = pcm*p_zLocal/p
868  //=======================================================
870  int itrack, bool isBarrel, unsigned int pcm, unsigned int pcmMin, const MPlexLV &pPar, const MPlexHS &msErr) {
871  //skip the overflow case
872  if (pcm >= Hit::maxChargePerCM())
873  return true;
874 
875  float qSF;
876  if (isBarrel) { //project in x,y, assuming zero-error direction is in this plane
877  const float hitT2 = msErr.constAt(itrack, 0, 0) + msErr.constAt(itrack, 1, 1);
878  const float hitT2inv = 1.f / hitT2;
879  const float proj[3] = {msErr.constAt(itrack, 0, 0) * hitT2inv,
880  msErr.constAt(itrack, 0, 1) * hitT2inv,
881  msErr.constAt(itrack, 1, 1) * hitT2inv};
882  const bool detXY_OK =
883  std::abs(proj[0] * proj[2] - proj[1] * proj[1]) < 0.1f; //check that zero-direction is close
884  const float cosP = cos(pPar.constAt(itrack, 4, 0));
885  const float sinP = sin(pPar.constAt(itrack, 4, 0));
886  const float sinT = std::abs(sin(pPar.constAt(itrack, 5, 0)));
887  //qSF = sqrt[(px,py)*(1-proj)*(px,py)]/p = sinT*sqrt[(cosP,sinP)*(1-proj)*(cosP,sinP)].
888  qSF = detXY_OK ? sinT * std::sqrt(std::abs(1.f + cosP * cosP * proj[0] + sinP * sinP * proj[2] -
889  2.f * cosP * sinP * proj[1]))
890  : 1.f;
891  } else { //project on z
892  // p_zLocal/p = p_z/p = cosT
893  qSF = std::abs(cos(pPar.constAt(itrack, 5, 0)));
894  }
895 
896  const float qCorr = pcm * qSF;
897  dprint("pcm " << pcm << " * " << qSF << " = " << qCorr << " vs " << pcmMin);
898  return qCorr > pcmMin;
899  }
900 
901  //==============================================================================
902  // FindCandidates - Standard Track Finding
903  //==============================================================================
904 
905  void MkFinder::findCandidates(const LayerOfHits &layer_of_hits,
906  std::vector<std::vector<TrackCand>> &tmp_candidates,
907  const int offset,
908  const int N_proc,
909  const FindingFoos &fnd_foos) {
910  // bool debug = true;
911 
912  MatriplexHitPacker mhp(layer_of_hits.hitArray());
913 
914  int maxSize = 0;
915 
916  // Determine maximum number of hits for tracks in the collection.
917  for (int it = 0; it < NN; ++it) {
918  if (it < N_proc) {
919  if (m_XHitSize[it] > 0) {
921  }
922  }
923  }
924 
925  dprintf("FindCandidates max hits to process=%d\n", maxSize);
926 
927  int nHitsAdded[NN]{};
928  bool isTooLargeCluster[NN]{false};
929 
930  for (int hit_cnt = 0; hit_cnt < maxSize; ++hit_cnt) {
931  mhp.reset();
932 
933  int charge_pcm[NN];
934 
935 #pragma omp simd
936  for (int itrack = 0; itrack < N_proc; ++itrack) {
937  if (hit_cnt < m_XHitSize[itrack]) {
938  const auto &hit = layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0));
939  mhp.addInputAt(itrack, hit);
940  charge_pcm[itrack] = hit.chargePerCM();
941  }
942  }
943 
944  mhp.pack(m_msErr, m_msPar);
945 
946  //now compute the chi2 of track state vs hit
947  MPlexQF outChi2;
948  MPlexLV propPar;
949  clearFailFlag();
950  (*fnd_foos.m_compute_chi2_foo)(m_Err[iP],
951  m_Par[iP],
952  m_Chg,
953  m_msErr,
954  m_msPar,
955  outChi2,
956  propPar,
957  m_FailFlag,
958  N_proc,
961 
962  // Now update the track parameters with this hit (note that some
963  // calculations are already done when computing chi2, to be optimized).
964  // 1. This is not needed for candidates the hit is not added to, but it's
965  // vectorized so doing it serially below should take the same time.
966  // 2. Still it's a waste of time in case the hit is not added to any of the
967  // candidates, so check beforehand that at least one cand needs update.
968  bool oneCandPassCut = false;
969  for (int itrack = 0; itrack < N_proc; ++itrack) {
970  float max_c2 = getHitSelDynamicChi2Cut(itrack, iP);
971 
972  if (hit_cnt < m_XHitSize[itrack]) {
973  const float chi2 = std::abs(outChi2[itrack]); //fixme negative chi2 sometimes...
974  dprint("chi2=" << chi2);
975  if (chi2 < max_c2) {
976  bool isCompatible = true;
977  if (!layer_of_hits.is_pixel()) {
978  //check module compatibility via long strip side = L/sqrt(12)
979  isCompatible =
980  isStripQCompatible(itrack, layer_of_hits.is_barrel(), m_Err[iP], propPar, m_msErr, m_msPar);
981 
982  //rescale strip charge to track parameters and reapply the cut
983  isCompatible &= passStripChargePCMfromTrack(
984  itrack, layer_of_hits.is_barrel(), charge_pcm[itrack], Hit::minChargePerCM(), propPar, m_msErr);
985  }
986  // Select only SiStrip hits with cluster size < maxClusterSize
987  if (!layer_of_hits.is_pixel()) {
988  if (layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0)).spanRows() >=
990  isTooLargeCluster[itrack] = true;
991  isCompatible = false;
992  }
993  }
994 
995  if (isCompatible) {
996  oneCandPassCut = true;
997  break;
998  }
999  }
1000  }
1001  }
1002 
1003  if (oneCandPassCut) {
1004  MPlexQI tmpChg = m_Chg;
1005  clearFailFlag();
1006  (*fnd_foos.m_update_param_foo)(m_Err[iP],
1007  m_Par[iP],
1008  tmpChg,
1009  m_msErr,
1010  m_msPar,
1011  m_Err[iC],
1012  m_Par[iC],
1013  m_FailFlag,
1014  N_proc,
1017 
1018  dprint("update parameters" << std::endl
1019  << "propagated track parameters x=" << m_Par[iP].constAt(0, 0, 0)
1020  << " y=" << m_Par[iP].constAt(0, 1, 0) << std::endl
1021  << " hit position x=" << m_msPar.constAt(0, 0, 0)
1022  << " y=" << m_msPar.constAt(0, 1, 0) << std::endl
1023  << " updated track parameters x=" << m_Par[iC].constAt(0, 0, 0)
1024  << " y=" << m_Par[iC].constAt(0, 1, 0));
1025 
1026  //create candidate with hit in case chi2 < max_c2
1027  //fixme: please vectorize me... (not sure it's possible in this case)
1028  for (int itrack = 0; itrack < N_proc; ++itrack) {
1029  float max_c2 = getHitSelDynamicChi2Cut(itrack, iP);
1030 
1031  if (hit_cnt < m_XHitSize[itrack]) {
1032  const float chi2 = std::abs(outChi2[itrack]); //fixme negative chi2 sometimes...
1033  dprint("chi2=" << chi2);
1034  if (chi2 < max_c2) {
1035  bool isCompatible = true;
1036  if (!layer_of_hits.is_pixel()) {
1037  //check module compatibility via long strip side = L/sqrt(12)
1038  isCompatible =
1039  isStripQCompatible(itrack, layer_of_hits.is_barrel(), m_Err[iP], propPar, m_msErr, m_msPar);
1040 
1041  //rescale strip charge to track parameters and reapply the cut
1042  isCompatible &= passStripChargePCMfromTrack(
1043  itrack, layer_of_hits.is_barrel(), charge_pcm[itrack], Hit::minChargePerCM(), propPar, m_msErr);
1044  }
1045  // Select only SiStrip hits with cluster size < maxClusterSize
1046  if (!layer_of_hits.is_pixel()) {
1047  if (layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0)).spanRows() >=
1049  isCompatible = false;
1050  }
1051 
1052  if (isCompatible) {
1053  bool hitExists = false;
1054  int maxHits = m_NFoundHits(itrack, 0, 0);
1055  if (layer_of_hits.is_pixel()) {
1056  for (int i = 0; i <= maxHits; ++i) {
1057  if (i > 2)
1058  break;
1059  if (m_HoTArrs[itrack][i].layer == layer_of_hits.layer_id()) {
1060  hitExists = true;
1061  break;
1062  }
1063  }
1064  }
1065  if (hitExists)
1066  continue;
1067 
1068  nHitsAdded[itrack]++;
1069  dprint("chi2 cut passed, creating new candidate");
1070  // Create a new candidate and fill the tmp_candidates output vector.
1071  // QQQ only instantiate if it will pass, be better than N_best
1072 
1073  const int hit_idx = m_XHitArr.At(itrack, hit_cnt, 0);
1074 
1075  TrackCand newcand;
1076  copy_out(newcand, itrack, iC);
1077  newcand.setCharge(tmpChg(itrack, 0, 0));
1078  newcand.addHitIdx(hit_idx, layer_of_hits.layer_id(), chi2);
1080  newcand,
1081  true /*penalizeTailMissHits*/,
1082  true /*inFindCandidates*/));
1083  newcand.setOriginIndex(m_CandIdx(itrack, 0, 0));
1084 
1085  // To apply a fixed cut instead of dynamic cut for overlap: m_iteration_params->chi2CutOverlap
1086  if (chi2 < max_c2) {
1087  CombCandidate &ccand = *newcand.combCandidate();
1088  ccand[m_CandIdx(itrack, 0, 0)].considerHitForOverlap(
1089  hit_idx, layer_of_hits.refHit(hit_idx).detIDinLayer(), chi2);
1090  }
1091 
1092  dprint("updated track parameters x=" << newcand.parameters()[0] << " y=" << newcand.parameters()[1]
1093  << " z=" << newcand.parameters()[2]
1094  << " pt=" << 1. / newcand.parameters()[3]);
1095 
1096  tmp_candidates[m_SeedIdx(itrack, 0, 0) - offset].emplace_back(newcand);
1097  }
1098  }
1099  }
1100  }
1101  } //end if (oneCandPassCut)
1102 
1103  } //end loop over hits
1104 
1105  //now add invalid hit
1106  //fixme: please vectorize me...
1107  for (int itrack = 0; itrack < N_proc; ++itrack) {
1108  // Cands that miss the layer are stashed away in MkBuilder(), before propagation,
1109  // and then merged back afterwards.
1110  if (m_XWsrResult[itrack].m_wsr == WSR_Outside) {
1111  continue;
1112  }
1113 
1114  int fake_hit_idx = ((num_all_minus_one_hits(itrack) < m_iteration_params->maxHolesPerCand) &&
1117  : Hit::kHitStopIdx;
1118 
1119  if (m_XWsrResult[itrack].m_wsr == WSR_Edge) {
1120  // YYYYYY m_iteration_params->store_missed_layers
1121  fake_hit_idx = Hit::kHitEdgeIdx;
1122  }
1123  //now add fake hit for tracks that passsed through inactive modules
1124  else if (m_XWsrResult[itrack].m_in_gap == true && nHitsAdded[itrack] == 0) {
1125  fake_hit_idx = Hit::kHitInGapIdx;
1126  }
1127  //now add fake hit for cases where hit cluster size is larger than maxClusterSize
1128  else if (isTooLargeCluster[itrack] == true && nHitsAdded[itrack] == 0) {
1129  fake_hit_idx = Hit::kHitMaxClusterIdx;
1130  }
1131 
1132  dprint("ADD FAKE HIT FOR TRACK #" << itrack << " withinBounds=" << (fake_hit_idx != Hit::kHitEdgeIdx)
1133  << " r=" << std::hypot(m_Par[iP](itrack, 0, 0), m_Par[iP](itrack, 1, 0)));
1134 
1135  // QQQ as above, only create and add if score better
1136  TrackCand newcand;
1137  copy_out(newcand, itrack, iP);
1138  newcand.addHitIdx(fake_hit_idx, layer_of_hits.layer_id(), 0.);
1139  newcand.setScore(getScoreCand(
1140  m_steering_params->m_track_scorer, newcand, true /*penalizeTailMissHits*/, true /*inFindCandidates*/));
1141  // Only relevant when we actually add a hit
1142  // newcand.setOriginIndex(m_CandIdx(itrack, 0, 0));
1143  tmp_candidates[m_SeedIdx(itrack, 0, 0) - offset].emplace_back(newcand);
1144  }
1145  }
1146 
1147  //==============================================================================
1148  // FindCandidatesCloneEngine - Clone Engine Track Finding
1149  //==============================================================================
1150 
1152  CandCloner &cloner,
1153  const int offset,
1154  const int N_proc,
1155  const FindingFoos &fnd_foos) {
1156  // bool debug = true;
1157 
1158  MatriplexHitPacker mhp(layer_of_hits.hitArray());
1159 
1160  int maxSize = 0;
1161 
1162  // Determine maximum number of hits for tracks in the collection.
1163 #pragma omp simd
1164  for (int it = 0; it < NN; ++it) {
1165  if (it < N_proc) {
1166  if (m_XHitSize[it] > 0) {
1168  }
1169  }
1170  }
1171 
1172  dprintf("FindCandidatesCloneEngine max hits to process=%d\n", maxSize);
1173 
1174  int nHitsAdded[NN]{};
1175  bool isTooLargeCluster[NN]{false};
1176 
1177  for (int hit_cnt = 0; hit_cnt < maxSize; ++hit_cnt) {
1178  mhp.reset();
1179 
1180  int charge_pcm[NN];
1181 
1182 #pragma omp simd
1183  for (int itrack = 0; itrack < N_proc; ++itrack) {
1184  if (hit_cnt < m_XHitSize[itrack]) {
1185  const auto &hit = layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0));
1186  mhp.addInputAt(itrack, hit);
1187  charge_pcm[itrack] = hit.chargePerCM();
1188  }
1189  }
1190 
1191  mhp.pack(m_msErr, m_msPar);
1192 
1193  //now compute the chi2 of track state vs hit
1194  MPlexQF outChi2;
1195  MPlexLV propPar;
1196  clearFailFlag();
1197  (*fnd_foos.m_compute_chi2_foo)(m_Err[iP],
1198  m_Par[iP],
1199  m_Chg,
1200  m_msErr,
1201  m_msPar,
1202  outChi2,
1203  propPar,
1204  m_FailFlag,
1205  N_proc,
1208 
1209 #pragma omp simd // DOES NOT VECTORIZE AS IT IS NOW
1210  for (int itrack = 0; itrack < N_proc; ++itrack) {
1211  // We can be in failed state from the initial propagation before selectHitIndices
1212  // and there hit_count for track is set to -1 and WSR state to Failed, handled below.
1213  // Or we might have hit it here in propagate-to-hit.
1214  // PROP-FAIL-ENABLE FailFlag check to be enabled when propagation failure
1215  // detection is properly implemented in propagate-to-R/Z.
1216  if ( hit_cnt < m_XHitSize[itrack]) {
1217  // make sure the hit was in the compatiblity window for the candidate
1218  const float max_c2 = getHitSelDynamicChi2Cut(itrack, iP);
1219  const float chi2 = std::abs(outChi2[itrack]); //fixme negative chi2 sometimes...
1220  // XXX-NUM-ERR assert(chi2 >= 0);
1221 
1222  dprint("chi2=" << chi2 << " for trkIdx=" << itrack << " hitIdx=" << m_XHitArr.At(itrack, hit_cnt, 0));
1223  if (chi2 < max_c2) {
1224  bool isCompatible = true;
1225  if (!layer_of_hits.is_pixel()) {
1226  //check module compatibility via long strip side = L/sqrt(12)
1227  isCompatible =
1228  isStripQCompatible(itrack, layer_of_hits.is_barrel(), m_Err[iP], propPar, m_msErr, m_msPar);
1229 
1230  //rescale strip charge to track parameters and reapply the cut
1231  isCompatible &= passStripChargePCMfromTrack(
1232  itrack, layer_of_hits.is_barrel(), charge_pcm[itrack], Hit::minChargePerCM(), propPar, m_msErr);
1233  }
1234 
1235  // Select only SiStrip hits with cluster size < maxClusterSize
1236  if (!layer_of_hits.is_pixel()) {
1237  if (layer_of_hits.refHit(m_XHitArr.At(itrack, hit_cnt, 0)).spanRows() >=
1239  isTooLargeCluster[itrack] = true;
1240  isCompatible = false;
1241  }
1242  }
1243 
1244  if (isCompatible) {
1245  CombCandidate &ccand = cloner.combCandWithOriginalIndex(m_SeedIdx(itrack, 0, 0));
1246  bool hitExists = false;
1247  int maxHits = m_NFoundHits(itrack, 0, 0);
1248  if (layer_of_hits.is_pixel()) {
1249  for (int i = 0; i <= maxHits; ++i) {
1250  if (i > 2)
1251  break;
1252  if (ccand.hot(i).layer == layer_of_hits.layer_id()) {
1253  hitExists = true;
1254  break;
1255  }
1256  }
1257  }
1258  if (hitExists)
1259  continue;
1260 
1261  nHitsAdded[itrack]++;
1262  const int hit_idx = m_XHitArr.At(itrack, hit_cnt, 0);
1263 
1264  // Register hit for overlap consideration, if chi2 cut is passed
1265  // To apply a fixed cut instead of dynamic cut for overlap: m_iteration_params->chi2CutOverlap
1266  if (chi2 < max_c2) {
1267  ccand[m_CandIdx(itrack, 0, 0)].considerHitForOverlap(
1268  hit_idx, layer_of_hits.refHit(hit_idx).detIDinLayer(), chi2);
1269  }
1270 
1271  IdxChi2List tmpList;
1272  tmpList.trkIdx = m_CandIdx(itrack, 0, 0);
1273  tmpList.hitIdx = hit_idx;
1274  tmpList.module = layer_of_hits.refHit(hit_idx).detIDinLayer();
1275  tmpList.nhits = m_NFoundHits(itrack, 0, 0) + 1;
1276  tmpList.ntailholes = 0;
1277  tmpList.noverlaps = m_NOverlapHits(itrack, 0, 0);
1278  tmpList.nholes = num_all_minus_one_hits(itrack);
1279  tmpList.pt = std::abs(1.0f / m_Par[iP].At(itrack, 3, 0));
1280  tmpList.chi2 = m_Chi2(itrack, 0, 0) + chi2;
1281  tmpList.chi2_hit = chi2;
1283  cloner.add_cand(m_SeedIdx(itrack, 0, 0) - offset, tmpList);
1284 
1285  dprint(" adding hit with hit_cnt=" << hit_cnt << " for trkIdx=" << tmpList.trkIdx
1286  << " orig Seed=" << m_Label(itrack, 0, 0));
1287  }
1288  }
1289  }
1290  }
1291 
1292  } //end loop over hits
1293 
1294  //now add invalid hit
1295  for (int itrack = 0; itrack < N_proc; ++itrack) {
1296  dprint("num_all_minus_one_hits(" << itrack << ")=" << num_all_minus_one_hits(itrack));
1297 
1298  // Cands that miss the layer are stashed away in MkBuilder(), before propagation,
1299  // and then merged back afterwards.
1300  if (m_XWsrResult[itrack].m_wsr == WSR_Outside) {
1301  continue;
1302  }
1303 
1304  // int fake_hit_idx = num_all_minus_one_hits(itrack) < m_iteration_params->maxHolesPerCand ? -1 : -2;
1305  int fake_hit_idx = ((num_all_minus_one_hits(itrack) < m_iteration_params->maxHolesPerCand) &&
1308  : Hit::kHitStopIdx;
1309 
1310  if (m_XWsrResult[itrack].m_wsr == WSR_Edge) {
1311  fake_hit_idx = Hit::kHitEdgeIdx;
1312  }
1313  //now add fake hit for tracks that passsed through inactive modules
1314  else if (m_XWsrResult[itrack].m_in_gap == true && nHitsAdded[itrack] == 0) {
1315  fake_hit_idx = Hit::kHitInGapIdx;
1316  }
1317  //now add fake hit for cases where hit cluster size is larger than maxClusterSize
1318  else if (isTooLargeCluster[itrack] == true && nHitsAdded[itrack] == 0) {
1319  fake_hit_idx = Hit::kHitMaxClusterIdx;
1320  }
1321 
1322  // PROP-FAIL-ENABLE The following to be enabled when propagation failure
1323  // detection is properly implemented in propagate-to-R/Z.
1324  // // Override for failed propagation, this trumps all other cases.
1325  // if (m_XWsrResult[itrack].m_wsr == WSR_Failed) {
1326  // fake_hit_idx = Hit::kHitStopIdx;
1327  // }
1328 
1329  IdxChi2List tmpList;
1330  tmpList.trkIdx = m_CandIdx(itrack, 0, 0);
1331  tmpList.hitIdx = fake_hit_idx;
1332  tmpList.module = -1;
1333  tmpList.nhits = m_NFoundHits(itrack, 0, 0);
1334  tmpList.ntailholes = (fake_hit_idx == Hit::kHitMissIdx ? m_NTailMinusOneHits(itrack, 0, 0) + 1
1335  : m_NTailMinusOneHits(itrack, 0, 0));
1336  tmpList.noverlaps = m_NOverlapHits(itrack, 0, 0);
1337  tmpList.nholes = num_inside_minus_one_hits(itrack);
1338  tmpList.pt = std::abs(1.0f / m_Par[iP].At(itrack, 3, 0));
1339  tmpList.chi2 = m_Chi2(itrack, 0, 0);
1340  tmpList.chi2_hit = 0;
1342  cloner.add_cand(m_SeedIdx(itrack, 0, 0) - offset, tmpList);
1343  dprint("adding invalid hit " << fake_hit_idx);
1344  }
1345  }
1346 
1347  //==============================================================================
1348  // UpdateWithLoadedHit
1349  //==============================================================================
1350 
1351  void MkFinder::updateWithLoadedHit(int N_proc, const FindingFoos &fnd_foos) {
1352  // See comment in MkBuilder::find_tracks_in_layer() about intra / inter flags used here
1353  // for propagation to the hit.
1354  clearFailFlag();
1355  (*fnd_foos.m_update_param_foo)(m_Err[iP],
1356  m_Par[iP],
1357  m_Chg,
1358  m_msErr,
1359  m_msPar,
1360  m_Err[iC],
1361  m_Par[iC],
1362  m_FailFlag,
1363  N_proc,
1366 
1367  // PROP-FAIL-ENABLE The following to be enabled when propagation failure
1368  // detection is properly implemented in propagate-to-R/Z.
1369  // for (int i = 0; i < N_proc; ++i) {
1370  // if (m_FailFlag[i]) {
1371  // dprintf("MkFinder::updateWithLoadedHit fail in update, recovering.\n");
1372  // m_Err[iC].copySlot(i, m_Err[iP]);
1373  // m_Par[iC].copySlot(i, m_Par[iP]);
1374  // }
1375  // }
1376  }
1377 
1378  //==============================================================================
1379  // CopyOutParErr
1380  //==============================================================================
1381 
1382  void MkFinder::copyOutParErr(std::vector<CombCandidate> &seed_cand_vec, int N_proc, bool outputProp) const {
1383  const int iO = outputProp ? iP : iC;
1384 
1385  for (int i = 0; i < N_proc; ++i) {
1386  TrackCand &cand = seed_cand_vec[m_SeedIdx(i, 0, 0)][m_CandIdx(i, 0, 0)];
1387 
1388  // Set the track state to the updated parameters
1389  m_Err[iO].copyOut(i, cand.errors_nc().Array());
1390  m_Par[iO].copyOut(i, cand.parameters_nc().Array());
1391  cand.setCharge(m_Chg(i, 0, 0));
1392 
1393  dprint((outputProp ? "propagated" : "updated")
1394  << " track parameters x=" << cand.parameters()[0] << " y=" << cand.parameters()[1]
1395  << " z=" << cand.parameters()[2] << " pt=" << 1. / cand.parameters()[3] << " posEta=" << cand.posEta());
1396  }
1397  }
1398 
1399  //==============================================================================
1400  // Backward Fit hack
1401  //==============================================================================
1402 
1403  void MkFinder::bkFitInputTracks(TrackVec &cands, int beg, int end) {
1404  // Uses HitOnTrack vector from Track directly + a local cursor array to current hit.
1405 
1406  MatriplexTrackPacker mtp(&cands[beg]);
1407 
1408  int itrack = 0;
1409 
1410  for (int i = beg; i < end; ++i, ++itrack) {
1411  const Track &trk = cands[i];
1412 
1413  m_Chg(itrack, 0, 0) = trk.charge();
1414  m_CurHit[itrack] = trk.nTotalHits() - 1;
1415  m_HoTArr[itrack] = trk.getHitsOnTrackArray();
1416 
1417  mtp.addInput(trk);
1418  }
1419 
1420  m_Chi2.setVal(0);
1421 
1422  mtp.pack(m_Err[iC], m_Par[iC]);
1423 
1424  m_Err[iC].scale(100.0f);
1425  }
1426 
1427  void MkFinder::bkFitInputTracks(EventOfCombCandidates &eocss, int beg, int end) {
1428  // Could as well use HotArrays from tracks directly + a local cursor array to last hit.
1429 
1430  // XXXX - shall we assume only TrackCand-zero is needed and that we can freely
1431  // bork the HoTNode array?
1432 
1433  MatriplexTrackPacker mtp(&eocss[beg][0]);
1434 
1435  int itrack = 0;
1436 
1437  for (int i = beg; i < end; ++i, ++itrack) {
1438  const TrackCand &trk = eocss[i][0];
1439 
1440  m_Chg(itrack, 0, 0) = trk.charge();
1441  m_CurNode[itrack] = trk.lastCcIndex();
1442  m_HoTNodeArr[itrack] = trk.combCandidate()->hotsData();
1443 
1444  // XXXX Need TrackCand* to update num-hits. Unless I collect info elsewhere
1445  // and fix it in BkFitOutputTracks.
1446  m_TrkCand[itrack] = &eocss[i][0];
1447 
1448  mtp.addInput(trk);
1449  }
1450 
1451  m_Chi2.setVal(0);
1452 
1453  mtp.pack(m_Err[iC], m_Par[iC]);
1454 
1455  m_Err[iC].scale(100.0f);
1456  }
1457 
1458  //------------------------------------------------------------------------------
1459 
1460  void MkFinder::bkFitOutputTracks(TrackVec &cands, int beg, int end, bool outputProp) {
1461  // Only copy out track params / errors / chi2, all the rest is ok.
1462 
1463  const int iO = outputProp ? iP : iC;
1464 
1465  int itrack = 0;
1466  for (int i = beg; i < end; ++i, ++itrack) {
1467  Track &trk = cands[i];
1468 
1469  m_Err[iO].copyOut(itrack, trk.errors_nc().Array());
1470  m_Par[iO].copyOut(itrack, trk.parameters_nc().Array());
1471 
1472  trk.setChi2(m_Chi2(itrack, 0, 0));
1473  if (isFinite(trk.chi2())) {
1475  }
1476  }
1477  }
1478 
1479  void MkFinder::bkFitOutputTracks(EventOfCombCandidates &eocss, int beg, int end, bool outputProp) {
1480  // Only copy out track params / errors / chi2, all the rest is ok.
1481 
1482  // XXXX - where will rejected hits get removed?
1483 
1484  const int iO = outputProp ? iP : iC;
1485 
1486  int itrack = 0;
1487  for (int i = beg; i < end; ++i, ++itrack) {
1488  TrackCand &trk = eocss[i][0];
1489 
1490  m_Err[iO].copyOut(itrack, trk.errors_nc().Array());
1491  m_Par[iO].copyOut(itrack, trk.parameters_nc().Array());
1492 
1493  trk.setChi2(m_Chi2(itrack, 0, 0));
1494  if (isFinite(trk.chi2())) {
1496  }
1497  }
1498  }
1499 
1500  //------------------------------------------------------------------------------
1501 
1502 #if defined(DEBUG_BACKWARD_FIT) || defined(DEBUG_BACKWARD_FIT_BH)
1503  namespace {
1504  float e2s(float x) { return 1e4 * std::sqrt(x); }
1505  } // namespace
1506 #endif
1507 
1508  void MkFinder::bkFitFitTracksBH(const EventOfHits &eventofhits,
1509  const SteeringParams &st_par,
1510  const int N_proc,
1511  bool chiDebug) {
1512  // Prototyping final backward fit.
1513  // This works with track-finding indices, before remapping.
1514  //
1515  // Layers should be collected during track finding and list all layers that have actual hits.
1516  // Then we could avoid checking which layers actually do have hits.
1517 
1518  MPlexQF tmp_chi2;
1519  float tmp_err[6] = {666, 0, 666, 0, 0, 666};
1520  float tmp_pos[3];
1521 
1522  for (auto lp_iter = st_par.m_layer_plan.rbegin(); lp_iter != st_par.m_layer_plan.rend(); ++lp_iter) {
1523  const int layer = lp_iter->m_layer;
1524 
1525  const LayerOfHits &L = eventofhits[layer];
1526  const LayerInfo &LI = *L.layer_info();
1527 
1528  int count = 0;
1529  for (int i = 0; i < N_proc; ++i) {
1530  while (m_CurHit[i] >= 0 && m_HoTArr[i][m_CurHit[i]].index < 0)
1531  --m_CurHit[i];
1532 
1533  if (m_CurHit[i] >= 0 && m_HoTArr[i][m_CurHit[i]].layer == layer) {
1534  // Skip the overlap hits -- if they exist.
1535  // 1. Overlap hit gets placed *after* the original hit in TrackCand::exportTrack()
1536  // which is *before* in the reverse iteration that we are doing here.
1537  // 2. Seed-hit merging can result in more than two hits per layer.
1538  while (m_CurHit[i] > 0 && m_HoTArr[i][m_CurHit[i] - 1].layer == layer)
1539  --m_CurHit[i];
1540 
1541  const Hit &hit = L.refHit(m_HoTArr[i][m_CurHit[i]].index);
1542  m_msErr.copyIn(i, hit.errArray());
1543  m_msPar.copyIn(i, hit.posArray());
1544  ++count;
1545  --m_CurHit[i];
1546  } else {
1547  tmp_pos[0] = m_Par[iC](i, 0, 0);
1548  tmp_pos[1] = m_Par[iC](i, 1, 0);
1549  tmp_pos[2] = m_Par[iC](i, 2, 0);
1550  m_msErr.copyIn(i, tmp_err);
1551  m_msPar.copyIn(i, tmp_pos);
1552  }
1553  }
1554 
1555  if (count == 0)
1556  continue;
1557 
1558  // ZZZ Could add missing hits here, only if there are any actual matches.
1559 
1560  if (LI.is_barrel()) {
1562 
1564  m_Err[iP],
1565  m_Par[iP],
1566  m_msErr,
1567  m_msPar,
1568  m_Err[iC],
1569  m_Par[iC],
1570  tmp_chi2,
1571  N_proc);
1572  } else {
1574 
1576  m_Err[iP],
1577  m_Par[iP],
1578  m_msErr,
1579  m_msPar,
1580  m_Err[iC],
1581  m_Par[iC],
1582  tmp_chi2,
1583  N_proc);
1584  }
1585 
1586  //fixup invpt sign and charge
1587  for (int n = 0; n < N_proc; ++n) {
1588  if (m_Par[iC].At(n, 3, 0) < 0) {
1589  m_Chg.At(n, 0, 0) = -m_Chg.At(n, 0, 0);
1590  m_Par[iC].At(n, 3, 0) = -m_Par[iC].At(n, 3, 0);
1591  }
1592  }
1593 
1594 #ifdef DEBUG_BACKWARD_FIT_BH
1595  // Dump per hit chi2
1596  for (int i = 0; i < N_proc; ++i) {
1597  float r_h = std::hypot(m_msPar.At(i, 0, 0), m_msPar.At(i, 1, 0));
1598  float r_t = std::hypot(m_Par[iC].At(i, 0, 0), m_Par[iC].At(i, 1, 0));
1599 
1600  // if ((std::isnan(tmp_chi2[i]) || std::isnan(r_t)))
1601  // if ( ! std::isnan(tmp_chi2[i]) && tmp_chi2[i] > 0) // && tmp_chi2[i] > 30)
1602  if (chiDebug) {
1603  int ti = iP;
1604  printf(
1605  "CHIHIT %3d %10g %10g %10g %10g %10g %11.5g %11.5g %11.5g %10g %10g %10g %10g %11.5g %11.5g %11.5g %10g "
1606  "%10g %10g %10g %10g %11.5g %11.5g\n",
1607  layer,
1608  tmp_chi2[i],
1609  m_msPar.At(i, 0, 0),
1610  m_msPar.At(i, 1, 0),
1611  m_msPar.At(i, 2, 0),
1612  r_h, // x_h y_h z_h r_h -- hit pos
1613  e2s(m_msErr.At(i, 0, 0)),
1614  e2s(m_msErr.At(i, 1, 1)),
1615  e2s(m_msErr.At(i, 2, 2)), // ex_h ey_h ez_h -- hit errors
1616  m_Par[ti].At(i, 0, 0),
1617  m_Par[ti].At(i, 1, 0),
1618  m_Par[ti].At(i, 2, 0),
1619  r_t, // x_t y_t z_t r_t -- track pos
1620  e2s(m_Err[ti].At(i, 0, 0)),
1621  e2s(m_Err[ti].At(i, 1, 1)),
1622  e2s(m_Err[ti].At(i, 2, 2)), // ex_t ey_t ez_t -- track errors
1623  1.0f / m_Par[ti].At(i, 3, 0),
1624  m_Par[ti].At(i, 4, 0),
1625  m_Par[ti].At(i, 5, 0), // pt, phi, theta
1626  std::atan2(m_msPar.At(i, 1, 0), m_msPar.At(i, 0, 0)), // phi_h
1627  std::atan2(m_Par[ti].At(i, 1, 0), m_Par[ti].At(i, 0, 0)), // phi_t
1628  1e4f * std::hypot(m_msPar.At(i, 0, 0) - m_Par[ti].At(i, 0, 0),
1629  m_msPar.At(i, 1, 0) - m_Par[ti].At(i, 1, 0)), // d_xy
1630  1e4f * (m_msPar.At(i, 2, 0) - m_Par[ti].At(i, 2, 0)) // d_z
1631  // e2s((m_msErr.At(i,0,0) + m_msErr.At(i,1,1)) / (r_h * r_h)), // ephi_h
1632  // e2s((m_Err[ti].At(i,0,0) + m_Err[ti].At(i,1,1)) / (r_t * r_t)) // ephi_t
1633  );
1634  }
1635  }
1636 #endif
1637 
1638  // update chi2
1639  m_Chi2.add(tmp_chi2);
1640  }
1641  }
1642 
1643  //------------------------------------------------------------------------------
1644 
1645  void MkFinder::print_par_err(int corp, int mslot) const {
1646 #ifdef DEBUG
1647  printf("Parameters:\n");
1648  for (int i = 0; i < 6; ++i) {
1649  printf(" %12.4g", m_Par[corp].constAt(mslot, i, 0));
1650  }
1651  printf("\nError matrix\n");
1652  for (int i = 0; i < 6; ++i) {
1653  for (int j = 0; j < 6; ++j) {
1654  printf(" %12.4g", m_Err[corp].constAt(mslot, i, j));
1655  }
1656  printf("\n");
1657  }
1658 #endif
1659  }
1660 
1661  void MkFinder::bkFitFitTracks(const EventOfHits &eventofhits,
1662  const SteeringParams &st_par,
1663  const int N_proc,
1664  bool chiDebug) {
1665  // Prototyping final backward fit.
1666  // This works with track-finding indices, before remapping.
1667  //
1668  // Layers should be collected during track finding and list all layers that have actual hits.
1669  // Then we could avoid checking which layers actually do have hits.
1670 
1671  // bool debug = true;
1672 
1673  MPlexQF tmp_chi2;
1674  MPlexQI no_mat_effs;
1675  float tmp_err[6] = {666, 0, 666, 0, 0, 666};
1676  float tmp_pos[3];
1677 
1678 #if defined(DEBUG_PROP_UPDATE)
1679  const int DSLOT = 0;
1680  printf("bkfit entry, track in slot %d\n", DSLOT);
1681  print_par_err(iC, DSLOT);
1682 #endif
1683 
1684  for (auto lp_iter = st_par.make_iterator(SteeringParams::IT_BkwFit); lp_iter.is_valid(); ++lp_iter) {
1685  const int layer = lp_iter.layer();
1686 
1687  const LayerOfHits &L = eventofhits[layer];
1688  const LayerInfo &LI = *L.layer_info();
1689 
1690 #if defined(DEBUG_BACKWARD_FIT)
1691  const Hit *last_hit_ptr[NN];
1692 #endif
1693 
1694  no_mat_effs.setVal(0);
1695  int done_count = 0;
1696  int here_count = 0;
1697  for (int i = 0; i < N_proc; ++i) {
1698  while (m_CurNode[i] >= 0 && m_HoTNodeArr[i][m_CurNode[i]].m_hot.index < 0) {
1700  }
1701 
1702  if (m_CurNode[i] < 0)
1703  ++done_count;
1704 
1705  if (m_CurNode[i] >= 0 && m_HoTNodeArr[i][m_CurNode[i]].m_hot.layer == layer) {
1706  // Skip the overlap hits -- if they exist.
1707  // 1. Overlap hit gets placed *after* the original hit in TrackCand::exportTrack()
1708  // which is *before* in the reverse iteration that we are doing here.
1709  // 2. Seed-hit merging can result in more than two hits per layer.
1710  // while (m_CurHit[i] > 0 && m_HoTArr[ i ][ m_CurHit[i] - 1 ].layer == layer) --m_CurHit[i];
1711  while (m_HoTNodeArr[i][m_CurNode[i]].m_prev_idx >= 0 &&
1712  m_HoTNodeArr[i][m_HoTNodeArr[i][m_CurNode[i]].m_prev_idx].m_hot.layer == layer)
1714 
1715  const Hit &hit = L.refHit(m_HoTNodeArr[i][m_CurNode[i]].m_hot.index);
1716 
1717 #ifdef DEBUG_BACKWARD_FIT
1718  last_hit_ptr[i] = &hit;
1719 #endif
1720  m_msErr.copyIn(i, hit.errArray());
1721  m_msPar.copyIn(i, hit.posArray());
1722  ++here_count;
1723 
1725  } else {
1726 #ifdef DEBUG_BACKWARD_FIT
1727  last_hit_ptr[i] = nullptr;
1728 #endif
1729  no_mat_effs[i] = 1;
1730  tmp_pos[0] = m_Par[iC](i, 0, 0);
1731  tmp_pos[1] = m_Par[iC](i, 1, 0);
1732  tmp_pos[2] = m_Par[iC](i, 2, 0);
1733  m_msErr.copyIn(i, tmp_err);
1734  m_msPar.copyIn(i, tmp_pos);
1735  }
1736  }
1737 
1738  if (done_count == N_proc)
1739  break;
1740  if (here_count == 0)
1741  continue;
1742 
1743  // ZZZ Could add missing hits here, only if there are any actual matches.
1744 
1745  clearFailFlag();
1746 
1747  // PROP-FAIL-ENABLE Once always "copy input to output on fail" is removed from
1748  // propagateToR one might want to enable this for barrel or endcap or both.
1749  if (LI.is_barrel()) {
1751 
1753  m_Err[iP],
1754  m_Par[iP],
1755  m_msErr,
1756  m_msPar,
1757  m_Err[iC],
1758  m_Par[iC],
1759  tmp_chi2,
1760  N_proc);
1761  } else {
1763 
1765  m_Err[iP],
1766  m_Par[iP],
1767  m_msErr,
1768  m_msPar,
1769  m_Err[iC],
1770  m_Par[iC],
1771  tmp_chi2,
1772  N_proc);
1773  }
1774 
1775 #if defined(DEBUG_PROP_UPDATE)
1776  printf("\nbkfit at layer %d, track in slot %d -- fail=%d, had hit=%d (%g, %g, %g)\n",
1777  LI.layer_id(),
1778  DSLOT,
1779  m_FailFlag[DSLOT],
1780  1 - no_mat_effs[DSLOT],
1781  m_msPar(DSLOT, 0, 0),
1782  m_msPar(DSLOT, 1, 0),
1783  m_msPar(DSLOT, 2, 0));
1784  printf("Propagated:\n");
1785  print_par_err(iP, DSLOT);
1786  printf("Updated:\n");
1787  print_par_err(iC, DSLOT);
1788 #endif
1789 
1790  // Fixup for failed propagation or invpt sign and charge.
1791  for (int i = 0; i < N_proc; ++i) {
1792  // PROP-FAIL-ENABLE The following to be enabled when propagation failure
1793  // detection is properly implemented in propagate-to-R/Z.
1794  // 1. The following code was only expecting barrel state to be restored.
1795  // auto barrel_pf(m_prop_config->backward_fit_pflags);
1796  // barrel_pf.copy_input_state_on_fail = true;
1797  // 2. There is also check on chi2, commented out to keep physics changes minimal.
1798  /*
1799  if (m_FailFlag[i] && LI.is_barrel()) {
1800  // Barrel pflags are set to include PF_copy_input_state_on_fail.
1801  // Endcap errors are immaterial here (relevant for fwd search), with prop error codes
1802  // one could do other things.
1803  // Are there also fail conditions in KalmanUpdate?
1804 #ifdef DEBUG
1805  if (debug && g_debug) {
1806  dprintf("MkFinder::bkFitFitTracks prop fail: chi2=%f, layer=%d, label=%d. Recovering.\n",
1807  tmp_chi2[i], LI.layer_id(), m_Label[i]);
1808  print_par_err(iC, i);
1809  }
1810 #endif
1811  m_Err[iC].copySlot(i, m_Err[iP]);
1812  m_Par[iC].copySlot(i, m_Par[iP]);
1813  } else if (tmp_chi2[i] > 200 || tmp_chi2[i] < 0) {
1814 #ifdef DEBUG
1815  if (debug && g_debug) {
1816  dprintf("MkFinder::bkFitFitTracks chi2 fail: chi2=%f, layer=%d, label=%d. Recovering.\n",
1817  tmp_chi2[i], LI.layer_id(), m_Label[i]);
1818  print_par_err(iC, i);
1819  }
1820 #endif
1821  // Go back to propagated state (at the current hit, the previous one is lost).
1822  m_Err[iC].copySlot(i, m_Err[iP]);
1823  m_Par[iC].copySlot(i, m_Par[iP]);
1824  }
1825  */
1826  // Fixup invpt sign and charge.
1827  if (m_Par[iC].At(i, 3, 0) < 0) {
1828  m_Chg.At(i, 0, 0) = -m_Chg.At(i, 0, 0);
1829  m_Par[iC].At(i, 3, 0) = -m_Par[iC].At(i, 3, 0);
1830  }
1831  }
1832 
1833 #if defined(DEBUG_BACKWARD_FIT)
1834  // clang-format off
1835  bool debug = true;
1836  const char beg_cur_sep = '/'; // set to ' ' root parsable printouts
1837  for (int i = 0; i < N_proc; ++i) {
1838  if (chiDebug && last_hit_ptr[i]) {
1839  TrackCand &bb = *m_TrkCand[i];
1840  int ti = iP;
1841  float chi = tmp_chi2.At(i, 0, 0);
1842  float chi_prnt = std::isfinite(chi) ? chi : -9;
1843 
1844 #if defined(MKFIT_STANDALONE)
1845  const MCHitInfo &mchi = m_event->simHitsInfo_[last_hit_ptr[i]->mcHitID()];
1846 
1847  dprintf("BKF_OVERLAP %d %d %d %d %d %d %d "
1848  "%f%c%f %f %f%c%f %f %f %f %d %d %d %d "
1849  "%f %f %f %f %f\n",
1850  m_event->evtID(),
1851 #else
1852  dprintf("BKF_OVERLAP %d %d %d %d %d %d "
1853  "%f%c%f %f %f%c%f %f %f %f %d %d %d "
1854  "%f %f %f %f %f\n",
1855 #endif
1856  bb.label(), (int)bb.prodType(), bb.isFindable(),
1857  layer, L.is_stereo(), L.is_barrel(),
1858  bb.pT(), beg_cur_sep, 1.0f / m_Par[ti].At(i, 3, 0),
1859  bb.posEta(),
1860  bb.posPhi(), beg_cur_sep, std::atan2(m_Par[ti].At(i, 1, 0), m_Par[ti].At(i, 0, 0)),
1861  std::hypot(m_Par[ti].At(i, 0, 0), m_Par[ti].At(i, 1, 0)),
1862  m_Par[ti].At(i, 2, 0),
1863  chi_prnt,
1864  std::isnan(chi), std::isfinite(chi), chi > 0,
1865 #if defined(MKFIT_STANDALONE)
1866  mchi.mcTrackID(),
1867 #endif
1868  // The following three can get negative / prouce nans in e2s.
1869  // std::abs the args for FPE hunt.
1870  e2s(std::abs(m_Err[ti].At(i, 0, 0))),
1871  e2s(std::abs(m_Err[ti].At(i, 1, 1))),
1872  e2s(std::abs(m_Err[ti].At(i, 2, 2))), // sx_t sy_t sz_t -- track errors
1873  1e4f * std::hypot(m_msPar.At(i, 0, 0) - m_Par[ti].At(i, 0, 0),
1874  m_msPar.At(i, 1, 0) - m_Par[ti].At(i, 1, 0)), // d_xy
1875  1e4f * (m_msPar.At(i, 2, 0) - m_Par[ti].At(i, 2, 0)) // d_z
1876  );
1877  }
1878  }
1879  // clang-format on
1880 #endif
1881 
1882  // update chi2
1883  m_Chi2.add(tmp_chi2);
1884  }
1885  }
1886 
1887  //------------------------------------------------------------------------------
1888 
1889  void MkFinder::bkFitPropTracksToPCA(const int N_proc) {
1891  }
1892 
1893 } // end namespace mkfit
float chi2_hit
Definition: Track.h:44
void setOriginIndex(int oi)
float getScoreCand(const track_score_func &score_func, const Track &cand1, bool penalizeTailMissHits=false, bool inFindCandidates=false)
Definition: Track.h:608
float x() const
Definition: Hit.h:162
void addHitIdx(int hitIdx, int hitLyr, float chi2)
def isnan(num)
MPlexQI m_Chg
Definition: MkBase.h:100
static constexpr int iC
Definition: MkBase.h:16
void copy_in(const Track &trk, const int mslot, const int tslot)
Definition: MkFinder.h:167
static constexpr int MPlexHitIdxMax
Definition: MkFinder.h:43
const SVector6 & parameters() const
Definition: Track.h:146
int charge() const
Definition: Track.h:185
MPlexQI m_NFoundHits
Definition: MkFinder.h:284
const IterationLayerConfig * m_iteration_layer_config
Definition: MkFinder.h:332
void setDiagonal3x3(idx_t n, T d)
Definition: MatriplexSym.h:201
const HitOnTrack * m_HoTArr[NN]
Definition: MkFinder.h:339
static constexpr int iP
Definition: MkBase.h:17
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:184
void copyIn(idx_t n, const T *arr)
Definition: Matriplex.h:70
void outputTracksAndHitIdx(std::vector< Track > &tracks, int beg, int end, bool outputProp) const
Definition: MkFinder.cc:166
float pT() const
Definition: Track.h:171
HitOnTrack m_HoTArrs[NN][Config::nMaxTrkHits]
Definition: MkFinder.h:286
const Hit * hitArray() const
Definition: HitStructures.h:98
void inputTracksAndHitIdx(const std::vector< Track > &tracks, int beg, int end, bool inputProp)
Definition: MkFinder.cc:53
void bkFitInputTracks(TrackVec &cands, int beg, int end)
Definition: MkFinder.cc:1403
void setup_bkfit(const PropagationConfig &pc, const SteeringParams &sp)
Definition: MkFinder.cc:35
void setChi2(float chi2)
Definition: Track.h:191
const T & constAt(idx_t n, idx_t i, idx_t j) const
Definition: Matriplex.h:52
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:99
PropagationFlags backward_fit_pflags
Definition: Config.h:34
MPlexQI m_FailFlag
Definition: MkBase.h:101
ProdType prodType() const
Definition: Track.h:263
bool is_pixel() const
T & At(idx_t n, idx_t i, idx_t j)
Definition: MatriplexSym.h:71
void selectHitIndices(const LayerOfHits &layer_of_hits, const int N_proc)
Definition: MkFinder.cc:248
int label() const
Definition: Track.h:188
void bkFitPropTracksToPCA(const int N_proc)
Definition: MkFinder.cc:1889
SMatrixSym66 & errors_nc()
Definition: Track.h:154
int mcTrackID() const
Definition: Hit.h:114
constexpr float PIOver2
Definition: Config.h:52
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:107
void release()
Definition: MkFinder.cc:40
void add_hit(const int mslot, int index, int layer)
Definition: MkFinder.h:236
float getEta(float r, float z)
Definition: Hit.h:38
assert(be >=bs)
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:20
float exx() const
Definition: Hit.h:165
Definition: Electron.h:6
const float * posArray() const
Definition: Hit.h:151
static unsigned int maxChargePerCM()
Definition: Hit.h:234
static constexpr int kHitStopIdx
Definition: Hit.h:194
const IterationParams * m_iteration_params
Definition: MkFinder.h:331
MPlexLS m_Err[2]
Definition: MkBase.h:98
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:905
static constexpr int kHitInGapIdx
Definition: Hit.h:197
const Double_t pi
track_score_func m_track_scorer
float ezz() const
Definition: Hit.h:167
constexpr bool usePhiQArrays
Definition: Config.h:112
float momEta() const
Definition: Track.h:175
const HoTNode * hotsData() const
PropagationFlags finding_inter_layer_pflags
Definition: Config.h:32
bool isStripQCompatible(int itrack, bool isBarrel, const MPlexLS &pErr, const MPlexLV &pPar, const MPlexHS &msErr, const MPlexHV &msPar)
Definition: MkFinder.cc:837
void setScore(float s)
Definition: Track.h:192
void add(const Matriplex &v)
Definition: Matriplex.h:37
float getScoreStruct(const track_score_func &score_func, const IdxChi2List &cand1)
Definition: Track.h:624
const PropagationConfig * m_prop_config
Definition: MkFinder.h:330
float posR() const
Definition: Track.h:163
iterator make_iterator(IterationType_e type) const
unsigned int module
Definition: Track.h:37
const T & constAt(idx_t n, idx_t i, idx_t j) const
Definition: MatriplexSym.h:69
int num_all_minus_one_hits(const int mslot) const
Definition: MkFinder.h:270
unsigned int detIDinLayer() const
Definition: Hit.h:228
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(* 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:21
int layer_id() const
Definition: TrackerInfo.h:56
float eyy() const
Definition: Hit.h:166
CombCandidate * combCandidate() const
Tan< T >::type tan(const T &t)
Definition: Tan.h:22
MPlexQI m_XHitSize
Definition: MkFinder.h:316
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
MPlexHV m_msPar
Definition: MkFinder.h:321
void propagateTracksToHitR(const MPlexHV &par, const int N_proc, const PropagationFlags pf, const MPlexQI *noMatEffPtr=nullptr)
Definition: MkBase.h:39
MPlexQI m_NTailMinusOneHits
Definition: MkFinder.h:306
double f[11][100]
bool isFindable() const
Definition: Track.h:256
void clearFailFlag()
Definition: MkBase.h:93
float ephi() const
Definition: Hit.h:172
void copyOut(idx_t n, T *arr) const
Definition: MatriplexSym.h:195
const HitOnTrack * getHitsOnTrackArray() const
Definition: Track.h:500
int m_CurNode[NN]
Definition: MkFinder.h:340
PropagationFlags pca_prop_pflags
Definition: Config.h:37
bool finding_requires_propagation_to_hit_pos
Definition: Config.h:31
float posEta() const
Definition: Track.h:166
constexpr float nSigmaPhi
float cdist(float a)
Definition: Config.h:75
int lastCcIndex() const
MPlexHS m_msErr
Definition: MkFinder.h:320
TrackCand * m_TrkCand[NN]
Definition: MkFinder.h:312
float y() const
Definition: Hit.h:163
std::vector< Track > TrackVec
#define debug
Definition: HDRShower.cc:19
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:1661
int m_CurHit[NN]
Definition: MkFinder.h:338
const SteeringParams * m_steering_params
Definition: MkFinder.h:333
static const FindingFoos & get_finding_foos(bool is_barrel)
Definition: FindingFoos.cc:18
void updateWithLoadedHit(int N_proc, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1351
float z() const
Definition: Track.h:162
std::vector< LayerControl > m_layer_plan
MPlexQI m_NOverlapHits
Definition: MkFinder.h:304
bool passStripChargePCMfromTrack(int itrack, bool isBarrel, unsigned int pcm, unsigned int pcmMin, const MPlexLV &pPar, const MPlexHS &msErr)
Definition: MkFinder.cc:869
float getPhi(float x, float y)
Definition: Hit.h:34
int nTotalHits() const
Definition: Track.h:519
MPlexHitIdx m_XHitArr
Definition: MkFinder.h:317
#define dprint(x)
Definition: Debug.h:95
MPlexQF m_Chi2
Definition: MkFinder.h:280
static constexpr int kHitMaxClusterIdx
Definition: Hit.h:196
void bkFitOutputTracks(TrackVec &cands, int beg, int end, bool outputProp)
Definition: MkFinder.cc:1460
void bkFitFitTracksBH(const EventOfHits &eventofhits, const SteeringParams &st_par, const int N_proc, bool chiDebug=false)
Definition: MkFinder.cc:1508
float z() const
Definition: Hit.h:164
void copyIn(idx_t n, const T *arr)
Definition: MatriplexSym.h:87
const std::vector< float > & get_window_params(bool forward, bool fallback_to_other) const
MPlexQI m_CandIdx
Definition: MkFinder.h:295
MPlexQI m_SeedIdx
Definition: MkFinder.h:294
HitOnTrack hot(int i) const
void copyOutParErr(std::vector< CombCandidate > &seed_cand_vec, int N_proc, bool outputProp) const
Definition: MkFinder.cc:1382
int num_inside_minus_one_hits(const int mslot) const
Definition: MkFinder.h:274
void findCandidatesCloneEngine(const LayerOfHits &layer_of_hits, CandCloner &cloner, const int offset, const int N_proc, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1151
void copyOut(idx_t n, T *arr) const
Definition: Matriplex.h:180
float x
const std::vector< bool > * m_iteration_hit_mask
Definition: MkFinder.h:334
bool is_barrel() const
PropagationFlags finding_intra_layer_pflags
Definition: Config.h:33
int layer_id() const
void setCharge(int chg)
Definition: Track.h:190
void add_cand(int idx, const IdxChi2List &cand_info)
Definition: CandCloner.h:34
float getHitSelDynamicChi2Cut(const int itrk, const int ipar)
Definition: MkFinder.cc:225
void setVal(T v)
Definition: Matriplex.h:31
static constexpr int kHitMissIdx
Definition: Hit.h:193
const HoTNode * m_HoTNodeArr[NN]
Definition: MkFinder.h:341
unsigned short bin_index_t
Definition: HitStructures.h:26
float momPhi() const
Definition: Track.h:174
WSR_Result m_XWsrResult[NN]
Definition: MkFinder.h:315
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:194
Geom::Theta< T > theta() const
static constexpr int kHitEdgeIdx
Definition: Hit.h:195
T & At(idx_t n, idx_t i, idx_t j)
Definition: Matriplex.h:54
CombCandidate & combCandWithOriginalIndex(int idx)
Definition: CandCloner.h:51
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:281
void propagateTracksToHitZ(const MPlexHV &par, const int N_proc, const PropagationFlags pf, const MPlexQI *noMatEffPtr=nullptr)
Definition: MkBase.h:65
bool is_barrel() const
Definition: TrackerInfo.h:68
void setup(const PropagationConfig &pc, const IterationParams &ip, const IterationLayerConfig &ilc, const SteeringParams &sp, const std::vector< bool > *ihm, bool infwd)
Definition: MkFinder.cc:21
void propagateTracksToPCAZ(const int N_proc, const PropagationFlags pf)
Definition: MkBase.h:79
const Hit & refHit(int i) const
Definition: HitStructures.h:97
void print_par_err(int corp, int mslot) const
Definition: MkFinder.cc:1645
void addBestHit(const LayerOfHits &layer_of_hits, const int N_proc, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:693
constexpr bool isFinite(float x)