All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
PMAlgTracking.cxx
Go to the documentation of this file.
1 ////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Class: PMAlgTracking
3 // Author: D.Stefan (Dorota.Stefan@ncbj.gov.pl),
4 // R.Sulej (Robert.Sulej@cern.ch),
5 // L.Whitehead (leigh.howard.whitehead@cern.ch), June 2016
6 ////////////////////////////////////////////////////////////////////////////////////////////////////
7 
11 
15 
16 #include "messagefacility/MessageLogger/MessageLogger.h"
17 
18 #include "TMath.h"
19 
23 
25 pma::convertFrom(const pma::Track3D& src, unsigned int tidx, int pdg)
26 {
27  std::vector<Point_t> positions;
28  positions.reserve(src.size());
29  std::vector<Vector_t> momenta;
30  momenta.reserve(src.size());
31  std::vector<recob::TrajectoryPointFlags> outFlags;
32  outFlags.reserve(src.size());
33 
34  for (size_t i = 0, h = 0; i < src.size(); i++)
35  if (src[i]->IsEnabled()) {
36  auto const& point3d = src[i]->Point3D();
37  positions.emplace_back(point3d.X(), point3d.Y(), point3d.Z());
38  momenta.push_back(src.GetDirection3D(i));
39  outFlags.emplace_back(h++, recob::TrajectoryPointFlags::makeMask());
40  }
41 
42  int ndof = 0;
43  float totChi2 = 0;
44 
45  SMatrixSym55 covStart, covEnd;
46  return recob::Track(
47  recob::TrackTrajectory(std::move(positions), std::move(momenta), std::move(outFlags), false),
48  pdg,
49  totChi2,
50  ndof,
51  covStart,
52  covEnd,
53  tidx);
54 }
55 // ------------------------------------------------------
56 
57 pma::PMAlgTrackingBase::PMAlgTrackingBase(const std::vector<art::Ptr<recob::Hit>>& allhitlist,
58  const pma::ProjectionMatchingAlg::Config& pmalgConfig,
59  const pma::PMAlgVertexing::Config& pmvtxConfig)
60  : fProjectionMatchingAlg(pmalgConfig), fPMAlgVertexing(pmvtxConfig)
61 {
62  unsigned int cryo, tpc, view;
63  for (auto const& h : allhitlist) {
64  cryo = h->WireID().Cryostat;
65  tpc = h->WireID().TPC;
66  view = h->WireID().Plane;
67 
68  fHitMap[cryo][tpc][view].push_back(h);
69  }
70 }
71 // ------------------------------------------------------
72 
74 {
75  for (auto t : fResult.tracks())
76  t.DeleteTrack();
77 }
78 // ------------------------------------------------------
79 
80 void
83 {
84  for (auto const& t : tracks.tracks()) {
85  auto& trk = *(t.Track());
86 
87  unsigned int tpc = trk.FrontTPC(), cryo = trk.FrontCryo();
88  if ((tpc == trk.BackTPC()) && (cryo == trk.BackCryo())) {
89  fProjectionMatchingAlg.guideEndpoints(detProp, trk, fHitMap[cryo][tpc]);
90  }
91  else {
92  fProjectionMatchingAlg.guideEndpoints(
93  detProp, trk, pma::Track3D::kBegin, fHitMap[trk.FrontCryo()][trk.FrontTPC()]);
94  fProjectionMatchingAlg.guideEndpoints(
95  detProp, trk, pma::Track3D::kEnd, fHitMap[trk.BackCryo()][trk.BackTPC()]);
96  }
97  }
98 }
99 // ------------------------------------------------------
100 // ------------------------------------------------------
101 // ------------------------------------------------------
102 
103 pma::PMAlgFitter::PMAlgFitter(const std::vector<art::Ptr<recob::Hit>>& allhitlist,
104  const std::vector<recob::Cluster>& clusters,
105  const std::vector<recob::PFParticle>& pfparticles,
106  const art::FindManyP<recob::Hit>& hitsFromClusters,
107  const art::FindManyP<recob::Cluster>& clusFromPfps,
108  const art::FindManyP<recob::Vertex>& vtxFromPfps,
109  const pma::ProjectionMatchingAlg::Config& pmalgConfig,
110  const pma::PMAlgFitter::Config& pmalgFitterConfig,
111  const pma::PMAlgVertexing::Config& pmvtxConfig)
112  : PMAlgTrackingBase(allhitlist, pmalgConfig, pmvtxConfig)
113  , fTrackingOnlyPdg(pmalgFitterConfig.TrackingOnlyPdg())
114  , fTrackingSkipPdg(pmalgFitterConfig.TrackingSkipPdg())
115  , fRunVertexing(pmalgFitterConfig.RunVertexing())
116 {
117  mf::LogVerbatim("PMAlgFitter") << "Found " << allhitlist.size() << "hits in the event.";
118  mf::LogVerbatim("PMAlgFitter") << "Sort hits by clusters assigned to PFParticles...";
119 
120  fCluHits.resize(clusters.size());
121  for (size_t i = 0; i < pfparticles.size(); ++i) {
122  fPfpPdgCodes[i] = pfparticles[i].PdgCode();
123 
124  auto cv = clusFromPfps.at(i);
125  for (const auto& c : cv) {
126  fPfpClusters[i].push_back(c);
127  if (fCluHits[c.key()].empty()) {
128  auto hv = hitsFromClusters.at(c.key());
129  fCluHits[c.key()].reserve(hv.size());
130  for (auto const& h : hv)
131  fCluHits[c.key()].push_back(h);
132  }
133  }
134 
135  if (vtxFromPfps.isValid() && vtxFromPfps.at(i).size()) {
136  double xyz[3];
137  vtxFromPfps.at(i).front()->XYZ(xyz);
138  fPfpVtx[i] = pma::Vector3D(xyz[0], xyz[1], xyz[2]);
139  }
140  }
141 
142  mf::LogVerbatim("PMAlgFitter") << "...done, " << fCluHits.size() << " clusters from "
143  << fPfpClusters.size() << " pfparticles for 3D tracking.";
144 }
145 // ------------------------------------------------------
146 
147 // ------------------------------------------------------
148 // ------------------------------------------------------
149 int
151 {
152  if (!fPfpClusters.empty() && !fCluHits.empty()) {
153  // build pm tracks
154  buildTracks(detProp);
155 
156  // add 3D ref.points for clean endpoints of wire-plae parallel tracks
157  guideEndpoints(detProp, fResult);
158 
159  if (fRunVertexing) fPMAlgVertexing.run(detProp, fResult);
160 
161  // build segment of shower
162  buildShowers(detProp);
163  }
164  else {
165  mf::LogWarning("PMAlgFitter") << "no clusters, no pfparticles";
166  return -1;
167  }
168 
169  return fResult.size();
170 }
171 // ------------------------------------------------------
172 // ------------------------------------------------------
173 
174 void
176 {
177  bool skipPdg = true;
178  if (!fTrackingSkipPdg.empty() && (fTrackingSkipPdg.front() == 0)) skipPdg = false;
179 
180  bool selectPdg = true;
181  if (!fTrackingOnlyPdg.empty() && (fTrackingOnlyPdg.front() == 0)) selectPdg = false;
182 
183  for (const auto& pfpCluEntry : fPfpClusters) {
184  int pfPartIdx = pfpCluEntry.first;
185  int pdg = fPfpPdgCodes[pfPartIdx];
186 
187  //if (pdg == 11) continue;
188  if (skipPdg && has(fTrackingSkipPdg, pdg)) continue;
189  if (selectPdg && !has(fTrackingOnlyPdg, pdg)) continue;
190 
191  mf::LogVerbatim("PMAlgFitter") << "Process clusters from PFP:" << pfPartIdx << ", pdg:" << pdg;
192 
193  std::vector<art::Ptr<recob::Hit>> allHits;
194 
195  pma::TrkCandidate candidate;
196  std::unordered_map<geo::View_t, size_t> clu_count;
197  for (const auto& c : pfpCluEntry.second) {
198  if (c->NHits() == 0) { continue; }
199 
200  candidate.Clusters().push_back(c.key());
201  clu_count[c->View()]++;
202 
203  allHits.reserve(allHits.size() + fCluHits.at(c.key()).size());
204  for (const auto& h : fCluHits.at(c.key())) {
205  allHits.push_back(h);
206  }
207  }
208  if (clu_count.size() > 1) // try building only if there are clusters from multiple views
209  {
210  candidate.SetKey(pfpCluEntry.first);
211 
212  candidate.SetTrack(fProjectionMatchingAlg.buildMultiTPCTrack(detProp, allHits));
213 
214  if (candidate.IsValid() && candidate.Track()->HasTwoViews() &&
215  (candidate.Track()->Nodes().size() > 1)) {
216  if (!std::isnan(candidate.Track()->Length())) { fResult.push_back(candidate); }
217  else {
218  mf::LogError("PMAlgFitter") << "Trajectory fit lenght is nan.";
219  candidate.DeleteTrack();
220  }
221  }
222  else {
223  candidate.DeleteTrack();
224  }
225  }
226  }
227 }
228 // ------------------------------------------------------
229 
230 void
232 {
233  bool skipPdg = true;
234  if (!fTrackingSkipPdg.empty() && (fTrackingSkipPdg.front() == 0)) skipPdg = false;
235 
236  bool selectPdg = true;
237  if (!fTrackingOnlyPdg.empty() && (fTrackingOnlyPdg.front() == 0)) selectPdg = false;
238 
239  for (const auto& pfpCluEntry : fPfpClusters) {
240  int pfPartIdx = pfpCluEntry.first;
241  int pdg = fPfpPdgCodes[pfPartIdx];
242 
243  if (pdg != 11) continue;
244  if (skipPdg && has(fTrackingSkipPdg, pdg)) continue;
245  if (selectPdg && !has(fTrackingOnlyPdg, pdg)) continue;
246 
247  mf::LogVerbatim("PMAlgFitter") << "Process clusters from PFP:" << pfPartIdx << ", pdg:" << pdg;
248 
249  std::vector<art::Ptr<recob::Hit>> allHits;
250 
251  pma::TrkCandidate candidate;
252  std::unordered_map<geo::View_t, size_t> clu_count;
253  for (const auto& c : pfpCluEntry.second) {
254  if (c->NHits() == 0) { continue; }
255 
256  candidate.Clusters().push_back(c.key());
257  clu_count[c->View()]++;
258 
259  allHits.reserve(allHits.size() + fCluHits.at(c.key()).size());
260  for (const auto& h : fCluHits.at(c.key()))
261  allHits.push_back(h);
262  }
263  if (clu_count.size() > 1) // try building only if there are clusters from multiple views
264  {
265  candidate.SetKey(pfpCluEntry.first);
266 
267  mf::LogVerbatim("PMAlgFitter") << "building..."
268  << ", pdg:" << pdg;
269 
270  auto search = fPfpVtx.find(pfPartIdx);
271  if (search != fPfpVtx.end()) {
272  candidate.SetTrack(fProjectionMatchingAlg.buildShowerSeg(detProp, allHits, search->second));
273 
274  if (candidate.IsValid() && candidate.Track()->HasTwoViews() &&
275  (candidate.Track()->Nodes().size() > 1) && !std::isnan(candidate.Track()->Length())) {
276  fResult.push_back(candidate);
277  }
278  else {
279  candidate.DeleteTrack();
280  }
281  }
282  }
283  }
284 }
285 // ------------------------------------------------------
286 // ------------------------------------------------------
287 // ------------------------------------------------------
288 
289 pma::PMAlgTracker::PMAlgTracker(const std::vector<art::Ptr<recob::Hit>>& allhitlist,
290  const std::vector<recob::Wire>& wires,
291  const pma::ProjectionMatchingAlg::Config& pmalgConfig,
292  const pma::PMAlgTracker::Config& pmalgTrackerConfig,
293  const pma::PMAlgVertexing::Config& pmvtxConfig,
294  const pma::PMAlgStitching::Config& pmstitchConfig,
295  const pma::PMAlgCosmicTagger::Config& pmtaggerConfig,
296 
297  const std::vector<TH1F*>& hpassing,
298  const std::vector<TH1F*>& hrejected)
299  : PMAlgTrackingBase(allhitlist, pmalgConfig, pmvtxConfig)
300  , fWires(wires)
301  , fMinSeedSize1stPass(pmalgTrackerConfig.MinSeedSize1stPass())
302  , fMinSeedSize2ndPass(pmalgTrackerConfig.MinSeedSize2ndPass())
303  , fTrackLikeThreshold(pmalgTrackerConfig.TrackLikeThreshold())
304  , fMinTwoViewFraction(pmalgConfig.MinTwoViewFraction())
305  , fFlipToBeam(pmalgTrackerConfig.FlipToBeam())
306  , fFlipDownward(pmalgTrackerConfig.FlipDownward())
307  , fFlipToX(pmalgTrackerConfig.FlipToX())
308  , fAutoFlip_dQdx(pmalgTrackerConfig.AutoFlip_dQdx())
309  , fMergeWithinTPC(pmalgTrackerConfig.MergeWithinTPC())
310  , fMergeTransverseShift(pmalgTrackerConfig.MergeTransverseShift())
311  , fMergeAngle(pmalgTrackerConfig.MergeAngle())
312  , fCosmicTagger(pmtaggerConfig)
313  , fTagCosmicTracks(fCosmicTagger.tagAny())
314  , fStitchBetweenTPCs(pmalgTrackerConfig.StitchBetweenTPCs())
315  , fStitchDistToWall(pmalgTrackerConfig.StitchDistToWall())
316  , fStitchTransverseShift(pmalgTrackerConfig.StitchTransverseShift())
317  , fStitchAngle(pmalgTrackerConfig.StitchAngle())
318  , fMatchT0inAPACrossing(pmalgTrackerConfig.MatchT0inAPACrossing())
319  , fMatchT0inCPACrossing(pmalgTrackerConfig.MatchT0inCPACrossing())
320  , fStitcher(pmstitchConfig)
321  , fRunVertexing(pmalgTrackerConfig.RunVertexing())
322  , fAdcInPassingPoints(hpassing)
323  , fAdcInRejectedPoints(hrejected)
324  , fGeom(&*(art::ServiceHandle<geo::Geometry const>()))
325 {
326  for (const auto v : fGeom->Views()) {
327  fAvailableViews.push_back(v);
328  }
329  std::reverse(fAvailableViews.begin(), fAvailableViews.end());
330 
331  mf::LogVerbatim("PMAlgTracker") << "Using views in the following order:";
332  for (const auto v : fAvailableViews) {
333  mf::LogInfo("PMAlgTracker") << " " << v;
334  }
335 
336  // ************************* track validation settings: **************************
337  mf::LogVerbatim("PMAlgTracker") << "Validation mode in config: "
338  << pmalgTrackerConfig.Validation();
339 
340  size_t nplanes = fGeom->MaxPlanes();
341  for (size_t p = 0; p < nplanes; ++p) {
342  fAdcImages.emplace_back(pmalgTrackerConfig.AdcImageAlg());
343  }
344 
345  if (pmalgTrackerConfig.Validation() == "hits") { fValidation = pma::PMAlgTracker::kHits; }
346  else if (pmalgTrackerConfig.Validation() == "adc") {
348  }
349  else if (pmalgTrackerConfig.Validation() == "calib") {
351  }
352  else {
353  throw cet::exception("pma::PMAlgTracker") << "validation name not supported" << std::endl;
354  }
355 
356  if ((nplanes < 3) && (fValidation != pma::PMAlgTracker::kHits)) {
357  mf::LogWarning("PMAlgTracker")
358  << "Not enough planes to perform validation, switch mode to hits.";
360  }
361 
362  fAdcValidationThr = pmalgTrackerConfig.AdcValidationThr();
364  mf::LogVerbatim("PMAlgTracker") << "Validation ADC thresholds per plane:";
365  for (auto thr : fAdcValidationThr) {
366  mf::LogVerbatim("PMAlgTracker") << " " << thr;
367  }
368  }
369 }
370 // ------------------------------------------------------
371 
372 void
373 pma::PMAlgTracker::init(const art::FindManyP<recob::Hit>& hitsFromClusters)
374 {
375  mf::LogVerbatim("PMAlgTracker") << "Sort hits by clusters...";
376  fCluHits.clear();
377  fCluHits.reserve(hitsFromClusters.size());
378  fCluWeights.clear();
379  fCluWeights.reserve(fCluHits.size());
380  for (size_t i = 0; i < hitsFromClusters.size(); ++i) {
381  auto v = hitsFromClusters.at(i);
382  fCluHits.push_back(std::vector<art::Ptr<recob::Hit>>());
383  for (auto const& h : v)
384  fCluHits.back().push_back(h);
385  fCluWeights.push_back(1);
386  }
387  mf::LogVerbatim("PMAlgTracker") << "...done, " << fCluHits.size() << " clusters for 3D tracking.";
388 }
389 // ------------------------------------------------------
390 
391 void
392 pma::PMAlgTracker::init(const art::FindManyP<recob::Hit>& hitsFromClusters,
393  const std::vector<float>& trackLike)
394 {
395  mf::LogVerbatim("PMAlgTracker") << "Filter track-like clusters using likelihood values...";
396  fCluHits.clear();
397  fCluHits.reserve(hitsFromClusters.size());
398  fCluWeights.clear();
399  fCluWeights.reserve(fCluHits.size());
400  for (size_t i = 0; i < hitsFromClusters.size(); ++i) {
401  auto v = hitsFromClusters.at(i);
402  fCluHits.push_back(std::vector<art::Ptr<recob::Hit>>());
403  for (auto const& h : v)
404  fCluHits.back().push_back(h);
405  fCluWeights.push_back(trackLike[i]);
406  }
407 }
408 // ------------------------------------------------------
409 
410 void
411 pma::PMAlgTracker::init(const art::FindManyP<recob::Hit>& hitsFromClusters,
412  const art::FindManyP<recob::Hit>& hitsFromEmParts)
413 {
414  mf::LogVerbatim("PMAlgTracker") << "Filter track-like clusters...";
415  fCluHits.clear();
416  fCluHits.reserve(hitsFromClusters.size());
417  fCluWeights.clear();
418  fCluWeights.reserve(fCluHits.size());
419  size_t n = 0; // count not-empty clusters
420  for (size_t i = 0; i < hitsFromClusters.size(); ++i) {
421  auto v = hitsFromClusters.at(i);
422  fCluHits.push_back(std::vector<art::Ptr<recob::Hit>>());
423  for (auto const& h : v) {
424  bool trkLike = true;
425  for (size_t j = 0; j < hitsFromEmParts.size(); ++j) {
426  auto u = hitsFromEmParts.at(j);
427  for (auto const& g : u) // is hit clustered in one of em-like?
428  {
429  if (g.key() == h.key()) {
430  trkLike = false;
431  break;
432  }
433  }
434  if (!trkLike) break;
435  }
436  if (trkLike) fCluHits.back().push_back(h);
437  }
438  if (!fCluHits.back().empty()) {
439  fCluWeights.push_back(1);
440  ++n;
441  }
442  else {
443  fCluWeights.push_back(0);
444  }
445  }
446  mf::LogVerbatim("PMAlgTracker") << "...done, " << n << " clusters for 3D tracking.";
447 }
448 // ------------------------------------------------------
449 
450 double
452  pma::Track3D& trk,
453  unsigned int testView)
454 {
455  if ((trk.FirstElement()->GetDistToWall() < -3.0) || (trk.LastElement()->GetDistToWall() < -3.0)) {
456  mf::LogVerbatim("PMAlgTracker") << "first or last node too far out of its initial TPC";
457  return 0.0;
458  }
459 
460  if (testView != geo::kUnknown) {
461  mf::LogVerbatim("PMAlgTracker") << "validation in plane: " << testView;
462  }
463  else {
464  return 1.0;
465  }
466 
467  double v = 0;
468  auto const& channelStatus = art::ServiceHandle<lariov::ChannelStatusService const> {}
469  ->GetProvider();
470  switch (fValidation) {
472  v = fProjectionMatchingAlg.validate_on_adc(
473  detProp, channelStatus, trk, fAdcImages[testView], fAdcValidationThr[testView]);
474  break;
475 
477  v = fProjectionMatchingAlg.validate(
478  detProp, channelStatus, trk, fHitMap[trk.FrontCryo()][trk.FrontTPC()][testView]);
479  break;
480 
482  v = fProjectionMatchingAlg.validate_on_adc_test(
483  detProp,
484  channelStatus,
485  trk,
486  fAdcImages[testView],
487  fHitMap[trk.FrontCryo()][trk.FrontTPC()][testView],
488  fAdcInPassingPoints[testView],
489  fAdcInRejectedPoints[testView]);
490  break;
491 
492  default:
493  throw cet::exception("pma::PMAlgTracker") << "validation mode not supported" << std::endl;
494  break;
495  }
496 
497  return v;
498 }
499 // ------------------------------------------------------
500 
501 bool
503  const std::vector<art::Ptr<recob::Hit>>& hits,
505  size_t trk_idx,
506  double dist2)
507 {
508  pma::Track3D* trk1 = tracks[trk_idx].Track();
509 
510  bool result = false;
511  if ((hits.size() > 1) || (dist2 > 1.0)) // min. 2 hits or single hit separated from the rest
512  {
513  pma::Track3D* best_trk = 0;
514 
515  size_t best_u = 0, n_max = 0;
516  for (size_t u = 0; u < tracks.size(); u++)
517  if (trk_idx != u) {
518  pma::Track3D* trk2 = tracks[u].Track();
519  size_t n = fProjectionMatchingAlg.testHits(detProp, *trk2, hits);
520  if (n > n_max) {
521  n_max = n;
522  best_u = u;
523  best_trk = trk2;
524  }
525  }
526 
527  if (best_trk && (n_max >= hits.size() / 3)) // /2
528  {
529  mf::LogVerbatim("PMAlgTrackMaker") << " Reassign(v1) " << n_max << " hits." << std::endl;
530 
531  trk1->RemoveHits(hits);
532  trk1->CleanupTails();
533  trk1->ShiftEndsToHits();
534 
535  pma::Track3D* ext = fProjectionMatchingAlg.extendTrack(detProp, *best_trk, hits, false);
536  ext->SortHits();
537  ext->ShiftEndsToHits();
538  if (fProjectionMatchingAlg.isContained(*ext)) {
539  tracks[best_u].SetTrack(ext); // and this deletes best_trk stored at best_u
540  result = true;
541  }
542  else
543  delete ext;
544  }
545  else if (hits.size() >= fMinSeedSize2ndPass) {
546  size_t minSizeCompl = hits.size() / 8; // much smaller minimum required in complementary views
547  if (minSizeCompl < 3) minSizeCompl = 3; // but at least three hits!
548 
549  geo::View_t first_view = (geo::View_t)hits.front()->WireID().Plane;
550  unsigned int tpc = hits.front()->WireID().TPC;
551  unsigned int cryo = hits.front()->WireID().Cryostat;
552 
553  pma::TrkCandidate candidate =
554  matchCluster(detProp, -1, hits, minSizeCompl, tpc, cryo, first_view);
555 
556  if (candidate.IsGood()) {
557  mf::LogVerbatim("PMAlgTrackMaker")
558  << " Add new track, cut hits from source track." << std::endl;
559  tracks.push_back(candidate);
560 
561  trk1->RemoveHits(hits);
562  trk1->CleanupTails();
563  trk1->ShiftEndsToHits();
564  }
565  }
566  }
567  else if ((hits.size() == 1) || (dist2 > 2.25)) // dist > 1.5cm
568  {
569  mf::LogVerbatim("PMAlgTrackMaker") << " Cut single-view isolated hit." << std::endl;
570  trk1->RemoveHits(hits);
571  trk1->CleanupTails();
572  trk1->ShiftEndsToHits();
573  }
574  return result;
575 }
576 
577 double
579  std::vector<art::Ptr<recob::Hit>>& hits) const
580 {
581  size_t idx = 0;
582  while ((idx < trk.size() - 1) && !(trk[idx]->IsEnabled())) {
583  hits.push_back(trk[idx++]->Hit2DPtr());
584  }
585 
586  double d2 = 0.0;
587  if (idx > 0) {
588  if ((idx < trk.size() - 1) && (trk[idx]->View2D() == trk[idx - 1]->View2D())) {
589  double dprev = pma::Dist2(trk[idx]->Point3D(), trk[idx - 1]->Point3D());
590  double dnext = pma::Dist2(trk[idx]->Point3D(), trk[idx + 1]->Point3D());
591  if (dprev < dnext) { hits.push_back(trk[idx++]->Hit2DPtr()); }
592  }
593  d2 = pma::Dist2(trk[idx]->Point3D(), trk[idx - 1]->Point3D());
594  }
595  return d2;
596 }
597 
598 double
600  std::vector<art::Ptr<recob::Hit>>& hits) const
601 {
602  size_t idx = trk.size() - 1;
603  while ((idx > 0) && !(trk[idx]->IsEnabled())) {
604  hits.push_back(trk[idx--]->Hit2DPtr());
605  }
606 
607  double d2 = 0.0;
608  if (idx < trk.size() - 1) {
609  if ((idx > 0) && (trk[idx]->View2D() == trk[idx + 1]->View2D())) {
610  double dprev = pma::Dist2(trk[idx]->Point3D(), trk[idx + 1]->Point3D());
611  double dnext = pma::Dist2(trk[idx]->Point3D(), trk[idx - 1]->Point3D());
612  if (dprev < dnext) { hits.push_back(trk[idx--]->Hit2DPtr()); }
613  }
614  d2 = pma::Dist2(trk[idx]->Point3D(), trk[idx + 1]->Point3D());
615  }
616  return d2;
617 }
618 
619 bool
622 {
623  bool result = false;
624  for (size_t t = 0; t < tracks.size(); t++) {
625  pma::Track3D& trk = *(tracks[t].Track());
626  if (trk.size() < 6) continue;
627 
628  trk.DisableSingleViewEnds();
629 
630  std::vector<art::Ptr<recob::Hit>> hits;
631 
632  double d2 = collectSingleViewEnd(trk, hits);
633  result |= reassignHits_1(detProp, hits, tracks, t, d2);
634 
635  hits.clear();
636 
637  d2 = collectSingleViewFront(trk, hits);
638  result |= reassignHits_1(detProp, hits, tracks, t, d2);
639 
640  trk.SelectHits();
641  }
642  return result;
643 }
644 
645 bool
647  pma::Track3D* trk2,
648  double& dist,
649  double& cos3d,
650  bool& reverseOrder,
651  double distThr,
652  double distThrMin,
653  double distProjThr,
654  double cosThr) const
655 {
656  double lmax;
657  double l1 = trk1->Length();
658  double l2 = trk2->Length();
659 
660  if (l1 > l2)
661  lmax = l1;
662  else
663  lmax = l2;
664 
665  double d = lmax * distThr;
666  if (d < distThrMin) d = distThrMin;
667 
668  unsigned int k = 0;
669  double distFF = pma::Dist2(trk1->front()->Point3D(), trk2->front()->Point3D());
670  dist = distFF;
671 
672  double distFB = pma::Dist2(trk1->front()->Point3D(), trk2->back()->Point3D());
673  if (distFB < dist) {
674  k = 1;
675  dist = distFB;
676  }
677 
678  double distBF = pma::Dist2(trk1->back()->Point3D(), trk2->front()->Point3D());
679  if (distBF < dist) {
680  k = 2;
681  dist = distBF;
682  }
683 
684  double distBB = pma::Dist2(trk1->back()->Point3D(), trk2->back()->Point3D());
685  if (distBB < dist) {
686  k = 3;
687  dist = distBB;
688  }
689 
690  dist = sqrt(dist);
691  cos3d = 0.0;
692 
693  if (dist < d) {
694  pma::Track3D* tmp = 0;
695  switch (k) // swap or flip to get trk1 end before trk2 start
696  {
697  case 0:
698  trk1->Flip(); // detProp);
699  break;
700  case 1:
701  tmp = trk1;
702  trk1 = trk2;
703  trk2 = tmp;
704  break;
705  case 2: break;
706  case 3:
707  trk2->Flip(); // detProp);
708  break;
709  default: mf::LogError("PMAlgTracker") << "Should never happen.";
710  }
711  if (k == 1)
712  reverseOrder = true;
713  else
714  reverseOrder = false;
715 
716  size_t nodeEndIdx = trk1->Nodes().size() - 1;
717 
718  TVector3 endpoint1 = trk1->back()->Point3D();
719  TVector3 trk2front0 = trk2->Nodes()[0]->Point3D();
720  TVector3 trk2front1 = trk2->Nodes()[1]->Point3D();
721  TVector3 proj1 = pma::GetProjectionToSegment(endpoint1, trk2front0, trk2front1);
722  double distProj1 = sqrt(pma::Dist2(endpoint1, proj1));
723 
724  TVector3 endpoint2 = trk2->front()->Point3D();
725  TVector3 trk1back0 = trk1->Nodes()[nodeEndIdx]->Point3D();
726  TVector3 trk1back1 = trk1->Nodes()[nodeEndIdx - 1]->Point3D();
727  TVector3 proj2 = pma::GetProjectionToSegment(endpoint2, trk1back1, trk1back0);
728  double distProj2 = sqrt(pma::Dist2(endpoint2, proj2));
729 
730  pma::Vector3D dir1 = trk1->Segments().back()->GetDirection3D();
731  pma::Vector3D dir2 = trk2->Segments().front()->GetDirection3D();
732 
733  cos3d = dir1.Dot(dir2);
734 
735  if ((cos3d > cosThr) && (distProj1 < distProjThr) && (distProj2 < distProjThr))
736  return true;
737  else // check if parallel to wires & colinear in 2D
738  {
739  const double maxCosXZ = 0.996195; // 5 deg
740 
741  pma::Vector3D dir1_xz(dir1.X(), 0., dir1.Z());
742  dir1_xz *= 1.0 / dir1_xz.R();
743 
744  pma::Vector3D dir2_xz(dir2.X(), 0., dir2.Z());
745  dir2_xz *= 1.0 / dir2_xz.R();
746 
747  if ((fabs(dir1_xz.Z()) > maxCosXZ) && (fabs(dir2_xz.Z()) > maxCosXZ)) {
748  endpoint1.SetY(0.);
749  trk2front0.SetY(0.);
750  trk2front1.SetY(0.);
751  proj1 = pma::GetProjectionToSegment(endpoint1, trk2front0, trk2front1);
752  distProj1 = sqrt(pma::Dist2(endpoint1, proj1));
753 
754  endpoint2.SetY(0.);
755  trk1back0.SetY(0.);
756  trk1back1.SetY(0.);
757  proj2 = pma::GetProjectionToSegment(endpoint2, trk1back1, trk1back0);
758  distProj2 = sqrt(pma::Dist2(endpoint2, proj2));
759 
760  double cosThrXZ = cos(0.5 * acos(cosThr));
761  double distProjThrXZ = 0.5 * distProjThr;
762  double cosXZ = dir1_xz.Dot(dir2_xz);
763  if ((cosXZ > cosThrXZ) && (distProj1 < distProjThrXZ) && (distProj2 < distProjThrXZ))
764  return true;
765  }
766  }
767  }
768  return false;
769 }
770 
771 bool
775 {
776  double distThr = 0.25; // max gap as a fraction of the longer track length
777  double distThrMin = 0.5; // lower limit of max gap threshold [cm]
778 
779  double distProjThr = fMergeTransverseShift;
780  double cosThr = cos(TMath::Pi() * fMergeAngle / 180.0);
781 
782  bool foundMerge = false;
783 
784  std::sort(tracks.tracks().begin(), tracks.tracks().end(), pma::bTrack3DLonger());
785 
786  bool r;
787  double d, dmin, c, cmax, l, lbest;
788  size_t t = 0, u = 0;
789  while (t < tracks.size()) {
790  pma::Track3D* trk1 = tracks[t].Track();
791 
792  pma::Track3D* trk2 = 0;
793  pma::Track3D* best_trk2 = 0;
794  dmin = 1.0e12;
795  cmax = 0;
796  lbest = 0;
797  size_t ubest = 0;
798  for (u = t + 1; u < tracks.size(); u++) {
799  trk2 = tracks[u].Track();
800  if (areCoLinear(trk1, trk2, d, c, r, distThr, distThrMin, distProjThr, cosThr)) {
801  l = std::sqrt(pma::Dist2(trk2->front()->Point3D(), trk2->back()->Point3D()));
802  if (((c > cmax) && (d < dmin + 0.5 * lbest)) || ((d < dmin) && (l > 1.5 * lbest))) {
803  cmax = c;
804  dmin = d;
805  best_trk2 = trk2;
806  lbest = l;
807  ubest = u;
808  }
809  }
810  trk2 = 0;
811  }
812  trk2 = best_trk2;
813 
814  if (trk2) {
815  mf::LogVerbatim("PMAlgTracker")
816  << "Merge track (" << trk1->size() << ") with track (" << trk2->size() << ")";
817  if (r) {
818  fProjectionMatchingAlg.mergeTracks(detProp, *trk2, *trk1, true);
819  tracks[t].SetTrack(trk2); // deletes old trk1
820  }
821  else {
822  fProjectionMatchingAlg.mergeTracks(detProp, *trk1, *trk2, true);
823  tracks[ubest].DeleteTrack();
824  }
825  tracks.erase_at(ubest);
826  foundMerge = true;
827  }
828  else
829  t++;
830  }
831 
832  return foundMerge;
833 }
834 // ------------------------------------------------------
835 
836 void
838 {
839  for (auto const& trk : tracks.tracks())
840  for (auto node : trk.Track()->Nodes())
841  if (node->IsBranching()) node->SetFrozen(true);
842 }
843 void
845 {
846  for (auto const& trk : tracks.tracks())
847  for (auto node : trk.Track()->Nodes())
848  node->SetFrozen(false);
849 }
850 
851 void
854  pma::tpc_track_map& tracks) const
855 {
856  double distThr = 0.25; // max gap as a fraction of the longer track length
857  double distThrMin = 2.5; // lower limit of max gap threshold [cm]
858 
859  double distProjThr = fStitchTransverseShift;
860  double cosThr = cos(TMath::Pi() * fStitchAngle / 180.0);
861 
862  double wallDistThr = fStitchDistToWall;
863  double dfront1, dback1, dfront2, dback2;
864 
865  for (auto& tpc_entry1 : tracks) {
866  unsigned int tpc1 = tpc_entry1.first;
867  pma::TrkCandidateColl& tracks1 = tpc_entry1.second;
868 
869  size_t t = 0;
870  while (t < tracks1.size()) {
871  bool r, reverse = false;
872  double l, lbest = 0, d, dmin = 1.0e12, c, cmax = 0.0;
873  pma::Track3D* best_trk2 = 0;
874  unsigned int best_tpc = 0;
875  size_t best_idx = 0;
876 
877  pma::Track3D* trk1 = tracks1[t].Track();
878  dfront1 = trk1->Nodes().front()->GetDistToWall();
879  dback1 = trk1->Nodes().back()->GetDistToWall();
880  if ((dfront1 < wallDistThr) || (dback1 < wallDistThr)) {
881  for (auto& tpc_entry2 : tracks) {
882  unsigned int tpc2 = tpc_entry2.first;
883  if (tpc2 == tpc1) continue;
884 
885  pma::TrkCandidateColl& tracks2 = tpc_entry2.second;
886 
887  for (size_t u = 0; u < tracks2.size(); u++) {
888  pma::Track3D* trk2 = tracks2[u].Track();
889  dfront2 = trk2->Nodes().front()->GetDistToWall();
890  dback2 = trk2->Nodes().back()->GetDistToWall();
891  if ((dfront2 < wallDistThr) || (dback2 < wallDistThr)) {
892  if (areCoLinear(trk1, trk2, d, c, r, distThr, distThrMin, distProjThr, cosThr)) {
893  l = std::sqrt(pma::Dist2(trk2->front()->Point3D(), trk2->back()->Point3D()));
894  if (((c > cmax) && (d < dmin + 0.5 * lbest)) || (0.75 * l < dmin)) {
895  cmax = c;
896  dmin = d;
897  lbest = l;
898  best_trk2 = trk2;
899  best_tpc = tpc2;
900  best_idx = u;
901  reverse = r;
902  }
903  }
904  }
905  }
906  }
907  }
908 
909  if (best_trk2) {
910  mf::LogVerbatim("PMAlgTracker")
911  << "Merge track (" << tpc1 << ":" << tracks1.size() << ":" << trk1->size()
912  << ") with track (" << best_tpc << ":" << tracks[best_tpc].size() << ":"
913  << best_trk2->size() << ")";
914  auto const* geom = lar::providerFrom<geo::Geometry>();
915  const geo::TPCGeo& tpc1 =
916  geom->TPC(trk1->Nodes().front()->TPC(), trk1->Nodes().front()->Cryo());
917  const geo::TPCGeo& tpc2 =
918  geom->TPC(best_trk2->Nodes().front()->TPC(), best_trk2->Nodes().front()->Cryo());
919  if (reverse) {
920  fProjectionMatchingAlg.mergeTracks(detProp, *best_trk2, *trk1, true);
921  // This track will have a shift in x equal to zero. This will
922  // properly set the track T0
923  if (tpc1.DetectDriftDirection() * tpc2.DetectDriftDirection() < 0) {
924  best_trk2->ApplyDriftShiftInTree(clockData, detProp, 0.0);
925  }
926  tracks1[t].SetTrack(best_trk2);
927  }
928  else {
929  fProjectionMatchingAlg.mergeTracks(detProp, *trk1, *best_trk2, true);
930  // This track will have a shift in x equal to zero. This will
931  // properly set the track T0
932  if (tpc1.DetectDriftDirection() * tpc2.DetectDriftDirection() < 0) {
933  trk1->ApplyDriftShiftInTree(clockData, detProp, 0.0);
934  }
935  tracks[best_tpc][best_idx].DeleteTrack();
936  }
937  tracks[best_tpc].erase_at(best_idx);
938  }
939  else
940  t++;
941  }
942  }
943 
944  //for (auto & tpc_entry : tracks) releaseAllNodes(tpc_entry.second);
945 }
946 // ------------------------------------------------------
947 
948 size_t
951  const std::vector<art::Ptr<recob::Hit>>& hits) const
952 {
953  size_t max_hits = 0;
954  for (auto const& t : tracks.tracks()) {
955  size_t n = fProjectionMatchingAlg.testHits(detProp, *(t.Track()), hits);
956  if (n > max_hits) { max_hits = n; }
957  }
958  return max_hits;
959 }
960 
961 // ------------------------------------------------------
962 // ------------------------------------------------------
963 int
966 {
967  fInitialClusters.clear();
968  fTriedClusters.clear();
969  fUsedClusters.clear();
970 
971  size_t nplanes = fGeom->MaxPlanes();
972 
973  pma::tpc_track_map tracks; // track parts in tpc's
974 
975  for (auto tpc_iter = fGeom->begin_TPC_id(); tpc_iter != fGeom->end_TPC_id(); tpc_iter++) {
976  mf::LogVerbatim("PMAlgTracker") << "Reconstruct tracks within Cryo:" << tpc_iter->Cryostat
977  << " / TPC:" << tpc_iter->TPC << ".";
978 
979  if (fValidation != pma::PMAlgTracker::kHits) // initialize ADC images for all planes in
980  // this TPC (in "adc" and "calib")
981  {
982  mf::LogVerbatim("PMAlgTracker") << "Prepare validation ADC images...";
983  bool ok = true;
984  for (size_t p = 0; p < nplanes; ++p) {
985  ok &= fAdcImages[p].setWireDriftData(
986  clockData, detProp, fWires, p, tpc_iter->TPC, tpc_iter->Cryostat);
987  }
988  if (ok) { mf::LogVerbatim("PMAlgTracker") << " ...done."; }
989  else {
990  mf::LogVerbatim("PMAlgTracker") << " ...failed.";
991  continue;
992  }
993  }
994 
995  // find reasonably large parts
996  fromMaxCluster_tpc(
997  detProp, tracks[tpc_iter->TPC], fMinSeedSize1stPass, tpc_iter->TPC, tpc_iter->Cryostat);
998  // loop again to find small things
999  fromMaxCluster_tpc(
1000  detProp, tracks[tpc_iter->TPC], fMinSeedSize2ndPass, tpc_iter->TPC, tpc_iter->Cryostat);
1001 
1002  //tryClusterLeftovers();
1003 
1004  mf::LogVerbatim("PMAlgTracker") << "Found tracks: " << tracks[tpc_iter->TPC].size();
1005  if (tracks[tpc_iter->TPC].empty()) { continue; }
1006 
1007  // add 3D ref.points for clean endpoints of wire-plane parallel track
1008  guideEndpoints(detProp, tracks[tpc_iter->TPC]);
1009  // try correcting single-view sections spuriously merged on 2D clusters
1010  // level
1011  reassignSingleViewEnds_1(detProp, tracks[tpc_iter->TPC]);
1012 
1013  if (fMergeWithinTPC) {
1014  mf::LogVerbatim("PMAlgTracker")
1015  << "Merge co-linear tracks within TPC " << tpc_iter->TPC << ".";
1016  while (mergeCoLinear(clockData, detProp, tracks[tpc_iter->TPC])) {
1017  mf::LogVerbatim("PMAlgTracker") << " found co-linear tracks";
1018  }
1019  }
1020  }
1021 
1022  if (fStitchBetweenTPCs) {
1023  mf::LogVerbatim("PMAlgTracker") << "Stitch co-linear tracks between TPCs.";
1024  mergeCoLinear(clockData, detProp, tracks);
1025  }
1026 
1027  for (auto& tpc_entry : tracks) // put tracks in the single collection
1028  for (auto& trk : tpc_entry.second.tracks()) {
1029  if (trk.Track()->HasTwoViews() && (trk.Track()->Nodes().size() > 1)) {
1030  fResult.push_back(trk);
1031  }
1032  else {
1033  trk.DeleteTrack();
1034  }
1035  }
1036 
1037  if (fTagCosmicTracks) {
1038  mf::LogVerbatim("PMAlgTracker") << "Tag cosmic tracks activity.";
1039  fCosmicTagger.tag(clockData, fResult);
1040  }
1041 
1042  if (fRunVertexing) {
1043  mf::LogVerbatim("PMAlgTracker") << "Vertex finding / track-vertex reoptimization.";
1044  fPMAlgVertexing.run(detProp, fResult);
1045  }
1046 
1047  fResult.setTreeIds();
1048 
1049  if (fMatchT0inCPACrossing) {
1050  mf::LogVerbatim("PMAlgTracker") << "Find co-linear CPA-crossing tracks with any T0.";
1051  fStitcher.StitchTracksCPA(clockData, detProp, fResult);
1052  }
1053 
1054  if (fMatchT0inAPACrossing) {
1055  mf::LogVerbatim("PMAlgTracker") << "Find co-linear APA-crossing tracks with any T0.";
1056  fStitcher.StitchTracksAPA(clockData, detProp, fResult);
1057  }
1058 
1059  if (fTagCosmicTracks) {
1060  mf::LogVerbatim("PMAlgTracker") << "Second pass cosmic tagging for stitched tracks";
1061  fCosmicTagger.tag(clockData, fResult);
1062  }
1063 
1064  if (fFlipToBeam)
1065  fResult.flipTreesToCoordinate(detProp,
1066  2); // flip the tracks / trees to the beam direction (Z)
1067  else if (fFlipDownward)
1068  fResult.flipTreesToCoordinate(detProp,
1069  1); // flip the tracks / trees to point downward (-Y)
1070  else if (fFlipToX)
1071  fResult.flipTreesToCoordinate(detProp,
1072  0); // flip the tracks / trees to point in -X
1073  // direction (downwards for dual phase)
1074 
1075  if (fAutoFlip_dQdx)
1076  fResult.flipTreesByDQdx(); // flip the tracks / trees to get best dQ/dx sequences
1077 
1078  fResult.setParentDaughterConnections();
1079 
1080  listUsedClusters(detProp);
1081  return fResult.size();
1082 }
1083 // ------------------------------------------------------
1084 // ------------------------------------------------------
1085 
1086 void
1088  pma::TrkCandidateColl& result,
1089  size_t minBuildSize,
1090  unsigned int tpc,
1091  unsigned int cryo)
1092 {
1093  fInitialClusters.clear();
1094 
1095  size_t minSizeCompl = minBuildSize / 8; // smaller minimum required in complementary views
1096  if (minSizeCompl < 2) minSizeCompl = 2; // but at least two hits!
1097 
1098  int max_first_idx = 0;
1099  while (max_first_idx >= 0) // loop over clusters, any view, starting from the largest
1100  {
1101  mf::LogVerbatim("PMAlgTracker") << "Find max cluster...";
1102  max_first_idx =
1103  maxCluster(minBuildSize, geo::kUnknown, tpc, cryo); // any view, but must be track-like
1104  if ((max_first_idx >= 0) && !fCluHits[max_first_idx].empty()) {
1105  geo::View_t first_view = fCluHits[max_first_idx].front()->View();
1106 
1107  pma::TrkCandidate candidate =
1108  matchCluster(detProp, max_first_idx, minSizeCompl, tpc, cryo, first_view);
1109 
1110  if (candidate.IsGood()) result.push_back(candidate);
1111  }
1112  else
1113  mf::LogVerbatim("PMAlgTracker") << "small clusters only";
1114  }
1115 
1116  fInitialClusters.clear();
1117 }
1118 // ------------------------------------------------------
1119 
1122  int first_clu_idx,
1123  const std::vector<art::Ptr<recob::Hit>>& first_hits,
1124  size_t minSizeCompl,
1125  unsigned int tpc,
1126  unsigned int cryo,
1127  geo::View_t first_view)
1128 {
1129  pma::TrkCandidate result;
1130 
1131  for (auto av : fAvailableViews) {
1132  fTriedClusters[av].clear();
1133  }
1134 
1135  if (first_clu_idx >= 0) {
1136  fTriedClusters[first_view].push_back((size_t)first_clu_idx);
1137  fInitialClusters.push_back((size_t)first_clu_idx);
1138  }
1139 
1140  unsigned int nFirstHits = first_hits.size(), first_plane_idx = first_hits.front()->WireID().Plane;
1141  mf::LogVerbatim("PMAlgTracker") << std::endl << "--- start new candidate ---";
1142  mf::LogVerbatim("PMAlgTracker") << "use view *** " << first_view << " *** plane idx "
1143  << first_plane_idx << " *** size: " << nFirstHits;
1144 
1145  float xmax = detProp.ConvertTicksToX(first_hits.front()->PeakTime(), first_plane_idx, tpc, cryo);
1146  float xmin = xmax;
1147  for (size_t j = 1; j < first_hits.size(); ++j) {
1148  float x = detProp.ConvertTicksToX(first_hits[j]->PeakTime(), first_plane_idx, tpc, cryo);
1149  if (x > xmax) { xmax = x; }
1150  if (x < xmin) { xmin = x; }
1151  }
1152 
1153  pma::TrkCandidateColl candidates; // possible solutions of the selected cluster and clusters in
1154  // complementary views
1155 
1156  size_t imatch = 0;
1157  bool try_build = true;
1158  while (try_build) // loop over complementary views
1159  {
1160  pma::TrkCandidate candidate;
1161  if (first_clu_idx >= 0) candidate.Clusters().push_back((size_t)first_clu_idx);
1162 
1163  try_build = false;
1164  int idx = -1, av_idx = -1;
1165  unsigned int nMaxHits = 0, nHits = 0;
1166  unsigned int testView = geo::kUnknown, bestView = geo::kUnknown;
1167  for (auto av : fAvailableViews) {
1168  if (av == first_view) continue;
1169 
1170  av_idx =
1171  maxCluster(detProp, first_clu_idx, candidates, xmin, xmax, minSizeCompl, av, tpc, cryo);
1172  if (av_idx >= 0) {
1173  nHits = fCluHits[av_idx].size();
1174  if ((nHits > nMaxHits) && (nHits >= minSizeCompl)) {
1175  nMaxHits = nHits;
1176  idx = av_idx;
1177  bestView = av;
1178  fTriedClusters[av].push_back(idx);
1179  try_build = true;
1180  }
1181  }
1182  }
1183  for (auto av : fAvailableViews) {
1184  if ((av != first_view) && (av != bestView)) {
1185  testView = av;
1186  break;
1187  }
1188  }
1189 
1190  if (try_build) {
1191  mf::LogVerbatim("PMAlgTracker") << "--> " << imatch++ << " match with:";
1192  mf::LogVerbatim("PMAlgTracker")
1193  << " cluster in view *** " << bestView << " *** size: " << nMaxHits;
1194 
1195  if (!fGeom->TPC(tpc, cryo).HasPlane(testView)) {
1196  mf::LogVerbatim("PMAlgTracker") << " no validation plane *** ";
1197  testView = geo::kUnknown;
1198  }
1199  else {
1200  mf::LogVerbatim("PMAlgTracker") << " validation plane *** " << testView << " ***";
1201  }
1202 
1203  double m0 = 0.0, v0 = 0.0;
1204  double mseThr = 0.15, validThr = 0.7; // cuts for a good track candidate
1205 
1206  candidate.Clusters().push_back(idx);
1207  candidate.SetTrack(fProjectionMatchingAlg.buildTrack(detProp, first_hits, fCluHits[idx]));
1208 
1209  if (candidate.IsValid() && // no track if hits from 2 views do not alternate
1210  fProjectionMatchingAlg.isContained(*(candidate.Track()), 2.0F)) // sticks out of TPC's?
1211  {
1212  m0 = candidate.Track()->GetMse();
1213  if (m0 < mseThr) // check validation only if MSE is OK - thanks for Tracy for noticing this
1214  {
1215  v0 = validate(detProp, *(candidate.Track()), testView);
1216  }
1217  }
1218 
1219  if (candidate.Track() && (m0 < mseThr) && (v0 > validThr)) // good candidate, try to extend it
1220  {
1221  mf::LogVerbatim("PMAlgTracker") << " good track candidate, MSE = " << m0 << ", v = " << v0;
1222 
1223  candidate.SetMse(m0);
1224  candidate.SetValidation(v0);
1225  candidate.SetGood(true);
1226 
1227  size_t minSize = 5; // min size for clusters matching
1228  double fraction = 0.5; // min fraction of close hits
1229 
1230  idx = 0;
1231  while (idx >= 0) // try to collect matching clusters, use **any** plane except validation
1232  {
1233  idx =
1234  matchCluster(detProp, candidate, minSize, fraction, geo::kUnknown, testView, tpc, cryo);
1235  if (idx >= 0) {
1236  // try building extended copy:
1237  // src, hits, valid.plane, add nodes
1238  if (extendTrack(detProp, candidate, fCluHits[idx], testView, true)) {
1239  candidate.Clusters().push_back(idx);
1240  }
1241  else
1242  idx = -1;
1243  }
1244  }
1245 
1246  mf::LogVerbatim("PMAlgTracker") << "merge clusters from the validation plane";
1247  fraction = 0.7; // only well matching the existing track
1248 
1249  idx = 0;
1250  bool extended = false;
1251  while ((idx >= 0) &&
1252  (testView != geo::kUnknown)) { // match clusters from the
1253  // plane used previously
1254  // for the validation
1255  idx =
1256  matchCluster(detProp, candidate, minSize, fraction, testView, geo::kUnknown, tpc, cryo);
1257  if (idx >= 0) {
1258  // validation not checked here, no new nodes:
1259  if (extendTrack(detProp, candidate, fCluHits[idx], geo::kUnknown, false)) {
1260  candidate.Clusters().push_back(idx);
1261  extended = true;
1262  }
1263  else
1264  idx = -1;
1265  }
1266  }
1267  // need to calculate again only if trk was extended w/o checking
1268  // validation:
1269  if (extended) candidate.SetValidation(validate(detProp, *(candidate.Track()), testView));
1270  }
1271  else {
1272  mf::LogVerbatim("PMAlgTracker") << "track REJECTED, MSE = " << m0 << "; v = " << v0;
1273  candidate.SetGood(false); // save also bad matches to avoid trying again
1274  // the same pair of clusters
1275  }
1276  candidates.push_back(candidate);
1277  }
1278  else {
1279  mf::LogVerbatim("PMAlgTracker") << "no matching clusters";
1280  }
1281  } // end loop over complementary views
1282 
1283  if (!candidates.empty()) // return best candidate, release other tracks and clusters
1284  {
1285  int best_trk = -1;
1286  double f, max_f = 0., min_mse = 10., max_v = 0.;
1287  for (size_t t = 0; t < candidates.size(); t++)
1288  if (candidates[t].IsGood() && (candidates[t].Track()->Nodes().size() > 1) &&
1289  candidates[t].Track()->HasTwoViews()) {
1290  f = fProjectionMatchingAlg.twoViewFraction(*(candidates[t].Track()));
1291 
1292  if ((f > max_f) || ((f == max_f) && ((candidates[t].Validation() > max_v) ||
1293  (candidates[t].Mse() < min_mse)))) {
1294  max_f = f;
1295  min_mse = candidates[t].Mse();
1296  max_v = candidates[t].Validation();
1297  best_trk = t;
1298  }
1299  }
1300 
1301  if ((best_trk > -1) && candidates[best_trk].IsGood() && (max_f > fMinTwoViewFraction)) {
1302  candidates[best_trk].Track()->ShiftEndsToHits();
1303 
1304  for (auto c : candidates[best_trk].Clusters())
1305  fUsedClusters.push_back(c);
1306 
1307  result = candidates[best_trk];
1308  }
1309 
1310  for (size_t t = 0; t < candidates.size(); t++) {
1311  if (int(t) != best_trk) candidates[t].DeleteTrack();
1312  }
1313  }
1314 
1315  return result;
1316 }
1317 // ------------------------------------------------------
1318 
1319 bool
1321  pma::TrkCandidate& candidate,
1322  const std::vector<art::Ptr<recob::Hit>>& hits,
1323  unsigned int testView,
1324  bool add_nodes)
1325 {
1326  double m_max = 2.0 * candidate.Mse(); // max acceptable MSE value
1327  if (m_max < 0.05) m_max = 0.05; // this is still good, low MSE value
1328 
1329  double v_min1 = 0.98 * candidate.Validation();
1330  double v_min2 = 0.9 * candidate.Validation();
1331 
1332  pma::Track3D* copy =
1333  fProjectionMatchingAlg.extendTrack(detProp, *(candidate.Track()), hits, add_nodes);
1334  double m1 = copy->GetMse();
1335  double v1 = validate(detProp, *copy, testView);
1336 
1337  if (((m1 < candidate.Mse()) && (v1 >= v_min2)) ||
1338  ((m1 < 0.5) && (m1 <= m_max) && (v1 >= v_min1))) {
1339  mf::LogVerbatim("PMAlgTracker") << " track EXTENDED, MSE = " << m1 << ", v = " << v1;
1340  candidate.SetTrack(copy); // replace with the new track (deletes old one)
1341  copy->SortHits(); // sort hits in the new track
1342 
1343  candidate.SetMse(m1); // save info
1344  candidate.SetValidation(v1);
1345 
1346  return true;
1347  }
1348  else {
1349  mf::LogVerbatim("PMAlgTracker") << " track NOT extended, MSE = " << m1 << ", v = " << v1;
1350  delete copy;
1351  return false;
1352  }
1353 }
1354 // ------------------------------------------------------
1355 
1356 int
1358  const pma::TrkCandidate& trk,
1359  size_t minSize,
1360  double fraction,
1361  unsigned int preferedView,
1362  unsigned int testView,
1363  unsigned int tpc,
1364  unsigned int cryo) const
1365 {
1366  double f, fmax = 0.0;
1367  unsigned int n, max = 0;
1368  int idx = -1;
1369  for (size_t i = 0; i < fCluHits.size(); ++i) {
1370  if (fCluHits[i].empty()) continue;
1371 
1372  unsigned int view = fCluHits[i].front()->View();
1373  unsigned int nhits = fCluHits[i].size();
1374 
1375  if (has(fUsedClusters, i) || // don't try already used clusters
1376  has(trk.Clusters(), i) || // don't try clusters from this candidate
1377  (view == testView) || // don't use clusters from validation view
1378  ((preferedView != geo::kUnknown) &&
1379  (view != preferedView)) || // only prefered view if specified
1380  (nhits < minSize)) // skip small clusters
1381  continue;
1382 
1383  n = fProjectionMatchingAlg.testHits(detProp, *(trk.Track()), fCluHits[i]);
1384  f = n / (double)nhits;
1385  if ((f > fraction) && (n > max)) {
1386  max = n;
1387  fmax = f;
1388  idx = i;
1389  }
1390  }
1391 
1392  if (idx >= 0)
1393  mf::LogVerbatim("PMAlgTracker") << "max matching hits: " << max << " (" << fmax << ")";
1394  else
1395  mf::LogVerbatim("PMAlgTracker") << "no clusters to extend the track";
1396 
1397  return idx;
1398 }
1399 // ------------------------------------------------------
1400 
1401 int
1403  int first_idx_tag,
1404  const pma::TrkCandidateColl& candidates,
1405  float xmin,
1406  float xmax,
1407  size_t min_clu_size,
1408  geo::View_t view,
1409  unsigned int tpc,
1410  unsigned int cryo) const
1411 {
1412  int idx = -1;
1413  size_t s_max = 0, s;
1414  double fraction = 0.0;
1415  float x;
1416 
1417  size_t first_idx = 0;
1418  bool has_first = false;
1419  if (first_idx_tag >= 0) {
1420  first_idx = (size_t)first_idx_tag;
1421  has_first = true;
1422  }
1423 
1424  for (size_t i = 0; i < fCluHits.size(); ++i) {
1425  if ((fCluHits[i].size() < min_clu_size) || (fCluHits[i].front()->View() != view) ||
1426  has(fUsedClusters, i) || has(fInitialClusters, i) || has(fTriedClusters[view], i))
1427  continue;
1428 
1429  bool pair_checked = false;
1430  for (auto const& c : candidates.tracks())
1431  if (has_first && has(c.Clusters(), first_idx) && has(c.Clusters(), i)) {
1432  pair_checked = true;
1433  break;
1434  }
1435  if (pair_checked) continue;
1436 
1437  const auto& v = fCluHits[i];
1438 
1439  if ((v.front()->WireID().TPC == tpc) && (v.front()->WireID().Cryostat == cryo)) {
1440  s = 0;
1441  for (size_t j = 0; j < v.size(); ++j) {
1442  x = detProp.ConvertTicksToX(v[j]->PeakTime(), v[j]->WireID().Plane, tpc, cryo);
1443  if ((x >= xmin) && (x <= xmax)) s++;
1444  }
1445 
1446  if (s > s_max) {
1447  s_max = s;
1448  idx = i;
1449  fraction = s / (double)v.size();
1450  }
1451  }
1452  }
1453  if (fraction > 0.4) return idx;
1454 
1455  return -1;
1456 }
1457 // ------------------------------------------------------
1458 
1459 int
1460 pma::PMAlgTracker::maxCluster(size_t min_clu_size,
1461  geo::View_t view,
1462  unsigned int tpc,
1463  unsigned int cryo) const
1464 {
1465  int idx = -1;
1466  size_t s_max = 0;
1467 
1468  for (size_t i = 0; i < fCluHits.size(); ++i) {
1469  const auto& v = fCluHits[i];
1470 
1471  if (v.empty() || (fCluWeights[i] < fTrackLikeThreshold) || has(fUsedClusters, i) ||
1472  has(fInitialClusters, i) || has(fTriedClusters[view], i) ||
1473  ((view != geo::kUnknown) && (v.front()->View() != view)))
1474  continue;
1475 
1476  if ((v.front()->WireID().TPC == tpc) && (v.front()->WireID().Cryostat == cryo)) {
1477  size_t s = v.size();
1478  if ((s >= min_clu_size) && (s > s_max)) {
1479  s_max = s;
1480  idx = i;
1481  }
1482  }
1483  }
1484  return idx;
1485 }
1486 // ------------------------------------------------------
1487 // ------------------------------------------------------
1488 
1489 void
1491 {
1492  mf::LogVerbatim("PMAlgTracker") << std::endl << "----------- matched clusters: -----------";
1493  for (size_t i = 0; i < fCluHits.size(); ++i) {
1494  if (!fCluHits[i].empty() && has(fUsedClusters, i)) {
1495  mf::LogVerbatim("PMAlgTracker")
1496  << " tpc: " << fCluHits[i].front()->WireID().TPC
1497  << ";\tview: " << fCluHits[i].front()->View() << ";\tsize: " << fCluHits[i].size()
1498  << ";\tweight: " << fCluWeights[i];
1499  }
1500  }
1501 
1502  mf::LogVerbatim("PMAlgTracker") << "--------- not matched clusters: ---------";
1503  size_t nsingles = 0;
1504  for (size_t i = 0; i < fCluHits.size(); ++i) {
1505  if (!fCluHits[i].empty() && !has(fUsedClusters, i)) {
1506  if (fCluHits[i].size() == 1) { nsingles++; }
1507  else {
1508  mf::LogVerbatim("PMAlgTracker")
1509  << " tpc: " << fCluHits[i].front()->WireID().TPC
1510  << ";\tview: " << fCluHits[i].front()->View() << ";\tsize: " << fCluHits[i].size()
1511  << ";\tweight: " << fCluWeights[i]
1512  << ";\tmatch: " << matchTrack(detProp, fResult, fCluHits[i]);
1513  }
1514  }
1515  }
1516  mf::LogVerbatim("PMAlgTracker") << " single hits: " << nsingles;
1517  mf::LogVerbatim("PMAlgTracker") << "-----------------------------------------";
1518 }
1519 // ------------------------------------------------------
1520 // ------------------------------------------------------
bool SelectHits(float fraction=1.0F)
pma::TrkCandidate matchCluster(detinfo::DetectorPropertiesData const &detProp, int first_clu_idx, const std::vector< art::Ptr< recob::Hit >> &first_hits, size_t minSizeCompl, unsigned int tpc, unsigned int cryo, geo::View_t first_view)
std::map< int, pma::Vector3D > fPfpVtx
void guideEndpoints(detinfo::DetectorPropertiesData const &detProp, pma::TrkCandidateColl &tracks)
size_t size() const
bool IsValid() const
bool areCoLinear(pma::Track3D *trk1, pma::Track3D *trk2, double &dist, double &cos3d, bool &reverseOrder, double distThr, double distThrMin, double distProjThr, double cosThr) const
double GetMse(unsigned int view=geo::kUnknown) const
MSE of hits weighted with hit amplidudes and wire plane coefficients.
BEGIN_PROLOG true icarus_rawdigitfilter FilterTools FilterPlane1 Plane
var pdg
Definition: selectors.fcl:14
ClusterModuleLabel join with tracks
static constexpr Mask_t makeMask(Flags...flags)
Returns a bit mask with only the specified bit set.
void SetKey(int key)
Set key of an external object associated to this track candidate.
recob::Track convertFrom(const pma::Track3D &src, unsigned int tidx, int pdg=0)
process_name opflash particleana ie x
geo::GeometryCore const * fGeom
size_t matchTrack(detinfo::DetectorPropertiesData const &detProp, const pma::TrkCandidateColl &tracks, const std::vector< art::Ptr< recob::Hit >> &hits) const
double Dist2(const TVector2 &v1, const TVector2 &v2)
void buildTracks(detinfo::DetectorPropertiesData const &detProp)
enum geo::_plane_proj View_t
Enumerate the possible plane projections.
ROOT::Math::SMatrix< Double32_t, 5, 5, ROOT::Math::MatRepSym< Double32_t, 5 > > SMatrixSym55
Definition: TrackingTypes.h:85
void ApplyDriftShiftInTree(const detinfo::DetectorClocksData &clockData, detinfo::DetectorPropertiesData const &detProp, double dx, bool skipFirst=false)
Unknown view.
Definition: geo_types.h:136
double validate(detinfo::DetectorPropertiesData const &detProp, pma::Track3D &trk, unsigned int testView)
bool IsGood() const
pma::Hit3D const * front() const
Definition: PmaTrack3D.h:101
bool reassignHits_1(detinfo::DetectorPropertiesData const &detProp, const std::vector< art::Ptr< recob::Hit >> &hits, pma::TrkCandidateColl &tracks, size_t trk_idx, double dist2)
void erase_at(size_t pos)
std::set< geo::View_t > const & Views() const
Returns a list of possible views in the detector.
Implementation of the Projection Matching Algorithm.
::fhicl::TupleAs< Point(::geo::Length_t,::geo::Length_t,::geo::Length_t)> Point3D
Atom object for reading a 3D point or vector (centimeters).
pdgs p
Definition: selectors.fcl:22
Geometry information for a single TPC.
Definition: TPCGeo.h:38
bool reassignSingleViewEnds_1(detinfo::DetectorPropertiesData const &detProp, pma::TrkCandidateColl &tracks)
std::map< size_t, pma::TrkCandidateColl > tpc_track_map
Definition: PMAlgTracking.h:54
fhicl::Atom< std::string > Validation
void SetGood(bool b)
std::vector< pma::Node3D * > const & Nodes() const noexcept
Definition: PmaTrack3D.h:338
TVector3 const & Point3D() const
Definition: PmaHit3D.h:55
std::size_t size(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:561
PMAlgTracker(const std::vector< art::Ptr< recob::Hit >> &allhitlist, const std::vector< recob::Wire > &wires, const pma::ProjectionMatchingAlg::Config &pmalgConfig, const pma::PMAlgTracker::Config &pmalgTrackerConfig, const pma::PMAlgVertexing::Config &pmvtxConfig, const pma::PMAlgStitching::Config &pmstitchConfig, const pma::PMAlgCosmicTagger::Config &pmtaggerConfig, const std::vector< TH1F * > &hpassing, const std::vector< TH1F * > &hrejected)
void SetValidation(double v)
void SetTrack(pma::Track3D *trk)
std::map< int, std::vector< art::Ptr< recob::Cluster > > > fPfpClusters
double Validation() const
int maxCluster(detinfo::DetectorPropertiesData const &detProp, int first_idx_tag, const pma::TrkCandidateColl &candidates, float xmin, float xmax, size_t min_clu_size, geo::View_t view, unsigned int tpc, unsigned int cryo) const
BEGIN_PROLOG g
recob::tracking::Vector_t Vector3D
pma::Vector3D GetDirection3D(size_t index) const
Get trajectory direction at given hit index.
Definition: PmaTrack3D.cxx:379
recob::tracking::Point_t Point_t
bool mergeCoLinear(detinfo::DetectorClocksData const &clockData, detinfo::DetectorPropertiesData const &detProp, pma::TrkCandidateColl &tracks) const
process_name pandoraGausCryo1 vertexChargeCryo1 vertexStubCryo1 xmin
std::vector< double > fAdcValidationThr
while getopts h
auto vector(Vector const &v)
Returns a manipulator which will print the specified array.
Definition: DumpUtils.h:265
int build(detinfo::DetectorPropertiesData const &detProp)
double GetDistToWall() const
Definition: PmaNode3D.cxx:82
ROOT::Math::DisplacementVector3D< ROOT::Math::Cartesian3D< Coord_t >, ROOT::Math::GlobalCoordinateSystemTag > Vector_t
Type for representation of momenta in 3D space. See recob::tracking::Coord_t for more details on the ...
Definition: TrackingTypes.h:29
fhicl::Sequence< double > AdcValidationThr
double collectSingleViewEnd(pma::Track3D &trk, std::vector< art::Ptr< recob::Hit >> &hits) const
unsigned int MaxPlanes() const
Returns the largest number of planes among all TPCs in this detector.
pma::Node3D * FirstElement() const
Definition: PmaTrack3D.h:343
std::map< int, int > fPfpPdgCodes
std::vector< pma::Segment3D * > const & Segments() const noexcept
Definition: PmaTrack3D.h:329
pma::Node3D * LastElement() const
Definition: PmaTrack3D.h:348
IDparameter< geo::WireID > WireID
Member type of validated geo::WireID parameter.
TVector2 GetProjectionToSegment(const TVector2 &p, const TVector2 &p0, const TVector2 &p1)
A trajectory in space reconstructed from hits.
PMAlgTrackingBase(const std::vector< art::Ptr< recob::Hit >> &allhitlist, const pma::ProjectionMatchingAlg::Config &pmalgConfig, const pma::PMAlgVertexing::Config &pmvtxConfig)
void SetMse(double m)
void RemoveHits(const std::vector< art::Ptr< recob::Hit >> &hits)
Remove hits; removes also hit-&gt;node/seg assignments.
Definition: PmaTrack3D.cxx:413
void fromMaxCluster_tpc(detinfo::DetectorPropertiesData const &detProp, pma::TrkCandidateColl &result, size_t minBuildSize, unsigned int tpc, unsigned int cryo)
unsigned int FrontTPC() const
Definition: PmaTrack3D.h:148
unsigned int FrontCryo() const
Definition: PmaTrack3D.h:153
unsigned int DisableSingleViewEnds()
PMAlgFitter(const std::vector< art::Ptr< recob::Hit >> &allhitlist, const std::vector< recob::Cluster > &clusters, const std::vector< recob::PFParticle > &pfparticles, const art::FindManyP< recob::Hit > &hitsFromClusters, const art::FindManyP< recob::Cluster > &clusFromPfps, const art::FindManyP< recob::Vertex > &vtxFromPfps, const pma::ProjectionMatchingAlg::Config &pmalgConfig, const pma::PMAlgFitter::Config &pmalgFitterConfig, const pma::PMAlgVertexing::Config &pmvtxConfig)
std::vector< std::vector< art::Ptr< recob::Hit > > > fCluHits
ClusterModuleLabel join with reoptimize track vertex structure MergeWithinTPC
double ConvertTicksToX(double ticks, int p, int t, int c) const
fhicl::Table< img::DataProviderAlg::Config > AdcImageAlg
bool HasTwoViews(size_t nmin=1) const
Definition: PmaTrack3D.cxx:443
recob::tracking::SMatrixSym55 SMatrixSym55
void CleanupTails()
Cut out tails with no hits assigned.
double Length(size_t step=1) const
Definition: PmaTrack3D.h:120
void freezeBranchingNodes(pma::TrkCandidateColl &tracks) const
Contains all timing reference information for the detector.
constexpr double dist(const TReal *x, const TReal *y, const unsigned int dimension)
void init(const art::FindManyP< recob::Hit > &hitsFromClusters)
short int DetectDriftDirection() const
Returns the expected drift direction based on geometry.
Definition: TPCGeo.cxx:157
then echo File list $list not found else cat $list while read file do echo $file sed s
Definition: file_to_url.sh:60
double collectSingleViewFront(pma::Track3D &trk, std::vector< art::Ptr< recob::Hit >> &hits) const
const std::vector< size_t > & Clusters() const
pma::Hit3D const * back() const
Definition: PmaTrack3D.h:106
T copy(T const &v)
void listUsedClusters(detinfo::DetectorPropertiesData const &detProp) const
int build(detinfo::DetectorClocksData const &clockData, detinfo::DetectorPropertiesData const &detProp)
std::vector< geo::View_t > fAvailableViews
void releaseAllNodes(pma::TrkCandidateColl &tracks) const
TrackCollectionProxyElement< TrackCollProxy > Track
Proxy to an element of a proxy collection of recob::Track objects.
bool extendTrack(detinfo::DetectorPropertiesData const &detProp, pma::TrkCandidate &candidate, const std::vector< art::Ptr< recob::Hit >> &hits, unsigned int testView, bool add_nodes)
pdgs k
Definition: selectors.fcl:22
bool Flip(const detinfo::DetectorPropertiesData &detProp, std::vector< pma::Track3D * > &allTracks)
Definition: PmaTrack3D.cxx:534
Interface for experiment-specific service for channel quality info.
EValidationMode fValidation
size_t size() const
Definition: PmaTrack3D.h:111
ROOT::Math::PositionVector3D< ROOT::Math::Cartesian3D< Coord_t >, ROOT::Math::GlobalCoordinateSystemTag > Point_t
Type for representation of position in physical 3D space. See recob::tracking::Coord_t for more detai...
Definition: TrackingTypes.h:26
pma::Track3D * Track() const
bool empty(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:555
esac echo uname r
bool ShiftEndsToHits()
recob::tracking::Vector_t Vector_t
ClusterModuleLabel RunVertexing
void push_back(const TrkCandidate &trk)
auto const detProp
Track from a non-cascading particle.A recob::Track consists of a recob::TrackTrajectory, plus additional members relevant for a &quot;fitted&quot; track:
std::vector< TrkCandidate > const & tracks() const
double Mse() const
pma::cryo_tpc_view_hitmap fHitMap
Definition: PMAlgTracking.h:93
ClusterModuleLabel join with reoptimize track vertex structure FlipToBeam
std::vector< img::DataProviderAlg > fAdcImages
void buildShowers(detinfo::DetectorPropertiesData const &detProp)