LArSoft  v09_90_00
Liquid Argon Software toolkit - https://larsoft.org/
GeoAlgo.cxx
Go to the documentation of this file.
2 #include "larcorealg/GeoAlgo/GeoAlgoConstants.h" // for kINVALID_DOUBLE
3 #include "larcorealg/GeoAlgo/GeoAlgoException.h" // for GeoAlgoException
4 
5 #include <stddef.h>
6 
7 namespace geoalgo {
8 
9  // Ref. RTCD 5.3.2 p. 177
10  // Intersection of a HalfLine w/ AABox
11  std::vector<Point_t> GeoAlgo::Intersection(const AABox_t& box,
12  const HalfLine_t& line,
13  bool back) const
14  {
15  // Result container
16  std::vector<Point_t> result;
17  Point_t xs1(3); // Only 2 points max possible
18  Point_t xs2(3); // Create in advance for early termination checks
19  // One-time only initialization for unit vectors
20  static std::vector<Point_t> min_plane_n;
21  static std::vector<Point_t> max_plane_n;
22  if (!min_plane_n.size()) {
23  min_plane_n.reserve(3);
24  min_plane_n.push_back(Vector_t(-1, 0, 0));
25  min_plane_n.push_back(Vector_t(0, -1, 0));
26  min_plane_n.push_back(Vector_t(0, 0, -1));
27  max_plane_n.reserve(3);
28  max_plane_n.push_back(Vector_t(1, 0, 0));
29  max_plane_n.push_back(Vector_t(0, 1, 0));
30  max_plane_n.push_back(Vector_t(0, 0, 1));
31  }
32  // min/max points of the AABox
33  auto const& min_pt = box.Min();
34  auto const& max_pt = box.Max();
35  // start/dir of the line
36  auto const& start = line.Start();
37  auto dir = line.Dir();
38  if (back) dir *= -1;
39  // Inspect the case of parallel line
40  for (size_t i = 0; i < min_pt.size(); ++i) {
41  if (dir[i] == 0 && (start[i] <= min_pt[i] || max_pt[i] <= start[i])) return result;
42  }
43  // Look for xs w/ 3 planes
44  for (size_t i = 0; i < 3; ++i) {
45  auto const& normal = min_plane_n[i];
46  double s = (-1.) * (normal * (start - min_pt)) / (normal * dir);
47  if (s < 0) continue;
48  auto xs = start + dir * s;
49  // Check if the found point is within the surface area of other 2 axis
50  bool on_surface = true;
51  for (size_t sur_axis = 0; sur_axis < 3; ++sur_axis) {
52  if (sur_axis == i) continue;
53  if (xs[sur_axis] < min_pt[sur_axis] || max_pt[sur_axis] < xs[sur_axis]) {
54  on_surface = false;
55  break;
56  }
57  }
58  if (on_surface && xs != xs1) {
59  // Directly assign to xs1 instead of making a copy
60  if (!(xs1.IsValid()))
61  for (size_t j = 0; j < 3; ++j)
62  xs1[j] = xs[j];
63  else {
64  // If xs2 is filled, no more point to search. Exit.
65  for (size_t j = 0; j < 3; ++j)
66  xs2[j] = xs[j];
67  break;
68  }
69  }
70  }
71  // If xs2 is filled, simply return the result. Order the output via distance
72  if (xs2.IsValid()) {
73  result.reserve(2);
74  if (xs1._SqDist_(start) > xs2._SqDist_(start)) std::swap(xs1, xs2);
75  result.push_back(xs1);
76  result.push_back(xs2);
77  return result;
78  }
79  // Look for xs w/ 3 planes
80  for (size_t i = 0; i < 3; ++i) {
81  auto const& normal = max_plane_n[i];
82  double s = (-1.) * (normal * (start - max_pt)) / (normal * dir);
83  if (s < 0) continue;
84  auto xs = start + dir * s;
85  bool on_surface = true;
86  for (size_t sur_axis = 0; sur_axis < 3; ++sur_axis) {
87  if (sur_axis == i) continue;
88  if (xs[sur_axis] < min_pt[sur_axis] || max_pt[sur_axis] < xs[sur_axis]) {
89  on_surface = false;
90  break;
91  }
92  }
93  if (on_surface && xs != xs1) {
94  if (!(xs1.IsValid()))
95  for (size_t j = 0; j < 3; ++j)
96  xs1[j] = xs[j];
97  else {
98  for (size_t j = 0; j < 3; ++j)
99  xs2[j] = xs[j];
100  break;
101  }
102  }
103  }
104  if (!xs1.IsValid()) return result;
105  if (xs2.IsValid()) {
106  result.reserve(2);
107  if (xs1._SqDist_(start) > xs2._SqDist_(start)) std::swap(xs1, xs2);
108  result.push_back(xs1);
109  result.push_back(xs2);
110  return result;
111  }
112  result.push_back(xs1);
113  return result;
114  }
115 
116  // AABox_t & LineSegment_t intersection search. Make a use of AABox_t & HalfLine_t function
117  std::vector<Point_t> GeoAlgo::Intersection(const AABox_t& box, const LineSegment_t& line) const
118  {
119  auto const& st = line.Start();
120  auto const& ed = line.End();
121  // Create a static HalfLine_t for this algorithm
122  static HalfLine_t hline(st, ed - st);
123  hline.Start(st[0], st[1], st[2]);
124  hline.Dir(ed[0] - st[0], ed[1] - st[1], ed[2] - st[2]);
125 
126  auto hline_result = Intersection(box, hline);
127 
128  if (!hline_result.size()) return hline_result;
129 
130  // For non-empty result, only keep ones that is within the line length
131  std::vector<Point_t> result;
132  auto length = st._SqDist_(ed);
133  for (auto const& pt : hline_result)
134  if (st._SqDist_(pt) < length) result.push_back(pt);
135  return result;
136  }
137 
138  // AABox_t & Trajectory_t intersection search. Make a use of AABox_t & HalfLine_t function
139  std::vector<Point_t> GeoAlgo::Intersection(const AABox_t& box, const Trajectory_t& trj) const
140  {
141 
142  std::vector<Point_t> result;
143  if (trj.size() < 2) return result; // If only 1 point, return
144  // Check compat
145  trj.compat(box.Min());
146  // Call the onetime-only HalfLine constructor
147  static HalfLine_t hline(trj[0], trj[1]);
148  for (size_t i = 0; i < trj.size() - 1; ++i) {
149 
150  auto const& st = trj[i];
151  auto const& ed = trj[i + 1];
152  hline.Start(st[0], st[1], st[2]);
153  hline.Dir(ed[0] - st[0], ed[1] - st[1], ed[2] - st[2]);
154 
155  auto hline_result = Intersection(box, hline);
156 
157  if (!hline_result.size()) continue;
158 
159  // Check if the length makes sense
160  auto length = st._SqDist_(ed);
161  for (auto const& pt : hline_result)
162  if (st._SqDist_(pt) < length) result.push_back(pt);
163  }
164  return result;
165  }
166 
167  // LineSegment sub-segment of HalfLine inside an AABox w/o checks
168  LineSegment_t GeoAlgo::BoxOverlap(const AABox_t& box, const HalfLine_t& line) const
169  {
170  // First find interection point of half-line and box
171  auto xs_v = Intersection(box, line);
172  if (xs_v.size() == 2) return LineSegment_t(xs_v[0], xs_v[1]);
173 
174  // Build a new LineSegment
175  if (!(xs_v.size())) return LineSegment_t();
176 
177  // Only other possiblity is # = 1
178  return LineSegment_t(line.Start(), xs_v[0]);
179  }
180 
182  Trajectory_t GeoAlgo::BoxOverlap(const AABox_t& box, const Trajectory_t& trj) const
183  {
184 
185  // if first & last points inside, then return full trajectory
186  if (box.Contain(trj[0]) and box.Contain(trj.back())) return trj;
187 
188  return trj;
189  }
190 
191  // Ref. RTCD 5.1.8 p. 146
192  // Distance between two infinite lines
193  double GeoAlgo::_SqDist_(const Line_t& l1, const Line_t& l2, Point_t& L1, Point_t& L2) const
194  {
195 
196  // closest approach when segment connecting the two lines
197  // is perpendicular to both lines
198 
199  // L1 = P1 + s(Q1-P1)
200  // L1 = P2 + t(Q2-P2)
201  // L1(s) and L2(t) are the closest approach points
202  // d1 = Q1-P1
203  // d2 = Q2-P2
204  // v(s,t) = L1(s) - L2(t)
205  // require d1*v == 0 && d2*v == 0
206  Vector_t d1 = l1.Pt2() - l1.Pt1();
207  Vector_t d2 = l2.Pt2() - l2.Pt1();
208  Vector_t r = l1.Pt1() - l2.Pt1();
209 
210  double a = d1 * d1;
211  double b = d1 * d2;
212  double c = d1 * r;
213  double e = d2 * d2;
214  double f = d2 * r;
215 
216  double d = a * e - b * b;
217 
218  // if d==0 the lines are parallel
219  // return Pt1 (doesn't matter) for line 1
220  // distance is distance between Pt1 of 1 line & second line
221  if (d == 0) {
222  L1 = l1.Pt1();
223  L2 = _ClosestPt_(l1.Pt1(), l2);
224  return L1._SqDist_(L2);
225  }
226 
227  double s = (b * f - c * e) / d;
228  double t = (a * f - b * c) / d;
229 
230  // s & t represent the paramteric points on the lines
231  // for the closest approach point
232  // now find the Point_t object at those locations
233 
234  L1 = l1.Pt1() + (l1.Pt2() - l1.Pt1()) * s;
235  L2 = l2.Pt1() + (l2.Pt2() - l2.Pt1()) * t;
236 
237  // find distance between these points
238  double dist = L1._SqDist_(L2);
239 
240  return dist;
241  }
242 
243  // Distance between two half-infinite lines
244  // use same function as for infinite lines
245  // but expect return points L1 and L2 to be
246  // "after" start point. Otherwise need
247  // to re-calculate using start point
248  // for one or both of the half-lines
249  double GeoAlgo::_SqDist_(const HalfLine_t& l1,
250  const HalfLine_t& l2,
251  Point_t& L1,
252  Point_t& L2) const
253  {
254 
255  //Same as for _SqDist_ with infinite line but check whether s & t go out of bounds (i.e. negative)
256 
257  Vector_t d1 = l1.Dir();
258  Vector_t d2 = l2.Dir();
259  Vector_t r = l1.Start() - l2.Start();
260 
261  double a = d1 * d1;
262  double b = d1 * d2;
263  double c = d1 * r;
264  double e = d2 * d2;
265  double f = d2 * r;
266 
267  double d = a * e - b * b;
268 
269  // Need to make sure d != 0
270  if (d == 0) {
271  // lines are parallel
272  // check closest distance from one start point
273  // to other line. Order indifferent
274  // Choose l1 to have cloest point be Start point
275  L1 = l1.Start();
276  L2 = _ClosestPt_(L1, l2);
277  return L1._SqDist_(L2);
278  }
279 
280  double s = (b * f - c * e) / d;
281  double t = (a * f - b * c) / d;
282 
283  // if s or t < 0, out of bounds for half-line
284  if (s < 0) s = 0;
285  if (t < 0) t = 0;
286 
287  // s & t represent the paramteric points on the lines
288  // for the closest approach point
289  // now find the Point_t object at those locations
290 
291  L1 = l1.Start() + l1.Dir() * s;
292  L2 = l2.Start() + l2.Dir() * t;
293 
294  // find distance between these points
295  double dist = L1._SqDist_(L2);
296 
297  return dist;
298  }
299 
300  // Distance between two half-infinite lines
301  // use same function as for infinite lines
302  // but expect return points L1 and L2 to be
303  // "after" start point. Otherwise need
304  // to re-calculate using start point
305  // for one or both of the half-lines
306  double GeoAlgo::_SqDist_(const HalfLine_t& hline,
307  const LineSegment_t& seg,
308  Point_t& L1,
309  Point_t& L2) const
310  {
311 
312  //Same as for _SqDist_ with infinite line but check whether s & t go out of bounds (i.e. negative)
313 
314  auto const d1 = hline.Dir();
315  auto const d2 = seg.End() - seg.Start();
316  auto const r = hline.Start() - seg.Start();
317 
318  double a = d1 * d1;
319  double b = d1 * d2;
320  double c = d1 * r;
321  double e = d2 * d2;
322  double f = d2 * r;
323 
324  double d = a * e - b * b;
325 
326  // if parallel then d == 0
327  if (d == 0) {
328  // distance is smallest quantity between:
329  // - distance from segment start to line
330  // - distance from segment end to line
331  double sDist = _SqDist_(seg.Start(), hline);
332  double eDist = _SqDist_(seg.End(), hline);
333  if (sDist <= eDist) {
334  // get closest point on line
335  L1 = _ClosestPt_(seg.Start(), hline);
336  L2 = seg.Start();
337  return sDist;
338  }
339  else {
340  L1 = _ClosestPt_(seg.End(), hline);
341  L2 = seg.End();
342  return eDist;
343  }
344  } // if parallel
345 
346  double s = (b * f - c * e) / d;
347 
348  // now check if parameters are out of bounds
349  if (s < 0) {
350  s = 0; // closest point on half-line is start
351  // re-evaluate closest point on segment using line start point
352  L1 = hline.Start();
353  L2 = _ClosestPt_(L1, seg);
354  return L1._SqDist_(L2);
355  }
356 
357  // if closest point is not beyond half-line
358  // it could be due to an intersection between half-line
359  // and segment projection.
360  // check value of t
361  double t = (a * f - b * c) / d;
362  // if t > 0 && < 1 then the two lines intersect. We are good!
363  if ((t < 1) and (t > 0)) {
364  L1 = hline.Start() + hline.Dir() * s;
365  L2 = seg.Start() + (seg.End() - seg.Start()) * t;
366  return L1._SqDist_(L2);
367  }
368  // if out of bounds clamp
369  // then re-evaluate closest point on line
370  t = _Clamp_(t, 0, 1);
371  L2 = seg.Start() + (seg.End() - seg.Start()) * t;
372  L1 = _ClosestPt_(L2, hline);
373  return L1._SqDist_(L2);
374  }
375 
376  // Ref. RTCD Ch 5.1 p. 130
377  double GeoAlgo::_SqDist_(const Point_t& pt, const Point_t& line_s, const Point_t& line_e) const
378  {
379  auto const ab = line_e - line_s;
380  auto const ac = pt - line_s;
381  auto const bc = pt - line_e;
382  auto e = ac * ab;
383  if (e <= 0.) return ac.SqLength();
384  auto f = ab.SqLength();
385  if (e >= f) return bc.SqLength();
386  return (ac.SqLength() - e * e / f);
387  }
388 
389  // Ref. RTCD Ch 5.1 p. 128-129
391  {
392 
393  auto const& ab = line.Dir();
394  // Project pt on line (ab), but deferring divide by ab * ab
395  auto t = ((pt - line.Start()) * ab);
396  // pt projects outside line, on the start side; clamp to start
397  if (t <= 0.)
398  return line.Start();
399  else {
400  auto denom = ab.SqLength();
401  // pt projects outside line, on the end side; clamp to end
402  if (t >= denom) return line.End();
403  // pt projects inside the line. must deferred divide now
404  else
405  return (line.Start() + ab * (t / denom));
406  }
407  }
408 
409  // Ref. RTCD Ch 5.1 p. 130
410  double GeoAlgo::_SqDist_(const Point_t& pt, const HalfLine_t& line) const
411  {
412  auto const& ab = line.Dir();
413  auto const ac = pt - line.Start();
414  auto const bc = ac - ab;
415 
416  auto e = ac * ab;
417  if (e <= 0.) return (ac * ac);
418  auto f = ab.SqLength();
419  return (ac.SqLength() - e * e / f);
420  }
421 
422  // Ref. RTCD Ch 5.1 p. 128-129
423  Point_t GeoAlgo::_ClosestPt_(const Point_t& pt, const HalfLine_t& line) const
424  {
425  auto const& ab = line.Dir();
426  auto t = (pt - line.Start()) * ab;
427  if (t <= 0.)
428  return line.Start();
429  else {
430  auto denom = ab.Length();
431  return (line.Start() + ab * (t / denom));
432  }
433  }
434 
435  // Point & Infinite Line min Distance
436  double GeoAlgo::_SqDist_(const Line_t& line, const Point_t& pt) const
437  {
438  auto const ab = line.Pt2() - line.Pt1();
439  auto const ac = pt - line.Pt1();
440  auto const bc = ac - ab;
441 
442  auto e = ac * ab;
443  auto f = ab.SqLength();
444  return (ac.SqLength() - e * e / f);
445  }
446 
447  // Point & Infinite Line Closest Point
448  Point_t GeoAlgo::_ClosestPt_(const Line_t& line, const Point_t& pt) const
449  {
450  auto const& ab = line.Pt2() - line.Pt1();
451  auto t = (pt - line.Pt1()) * ab;
452  auto denom = ab.Length();
453  return (line.Pt1() + ab * (t / denom));
454  }
455 
456  // Ref. RTCD Ch 5.1 p. 131-132 ... modified to consider distance to the box's wall
457  double GeoAlgo::_SqDist_(const Point_t& pt, const AABox_t& box) const
458  {
459  double dist = kINVALID_DOUBLE;
460 
461  // If a point is inside the box, simply compute the smallest perpendicular distance
462  if (box.Contain(pt)) {
463 
464  auto const& pt_min = box.Min();
465  auto const& pt_max = box.Max();
466  // (1) Compute the distance to the YZ wall
467  double dist_to_yz = pt[0] - pt_min[0];
468  if (dist_to_yz > (pt_max[0] - pt[0])) dist_to_yz = pt_max[0] - pt[0];
469 
470  // (2) Compute the distance to the XZ wall
471  double dist_to_zx = pt[1] - pt_min[1];
472  if (dist_to_zx > (pt_max[1] - pt[1])) dist_to_zx = pt_max[1] - pt[1];
473 
474  // (3) Compute the distance to the XY wall
475  double dist_to_xy = pt[2] - pt_min[2];
476  if (dist_to_xy > (pt_max[2] - pt[2])) dist_to_xy = pt_max[2] - pt[2];
477 
478  // (4) Compute the minimum of (3), (4), and (5)
479  dist = (dist_to_yz < dist_to_zx ? dist_to_yz : dist_to_zx);
480  dist = (dist < dist_to_xy ? dist : dist_to_xy);
481  dist *= dist;
482  }
483 
484  else {
485  // This refers to Ref. RTCD 5.1.3.1
486  // re-set distance
487  dist = 0;
488  for (size_t i = 0; i < pt.size(); ++i) {
489 
490  auto const& v_pt = pt[i];
491  auto const& v_max = box.Max()[i];
492  auto const& v_min = box.Min()[i];
493 
494  if (v_pt < v_min) dist += (v_min - v_pt) * (v_min - v_pt);
495  if (v_pt > v_max) dist += (v_pt - v_max) * (v_pt - v_max);
496  }
497  }
498  return dist;
499  }
500 
501  // Ref. RTCD Ch 5.1 p. 130-131 ... modified to consider a point on the surface
502  Point_t GeoAlgo::_ClosestPt_(const Point_t& pt, const AABox_t& box) const
503  {
504  // Result
505  auto res = pt;
506  // For each coordinate axis, if the point coordinate value is outside box,
507  // clamp it to the box, else keep it as is
508  for (size_t i = 0; i < pt.size(); ++i) {
509  auto const& v_pt = pt[i];
510  auto const& v_min = box.Min()[i];
511  auto const& v_max = box.Max()[i];
512  res[i] = v_pt;
513  if (v_pt < v_min) res[i] = v_min;
514  if (v_pt > v_max) res[i] = v_max;
515  }
516  return res;
517  }
518 
519  // Distance between a Trajectory_t and a Point_t
520  // Loop over segments that make up the trajectory and keep track
521  // of shortest distance between any of them and the point
522  // The smallest such distance is the return
523  double GeoAlgo::SqDist(const Point_t& pt, const Trajectory_t& trj) const
524  {
525 
526  // Make sure trajectory object is properly defined
527  if (!trj.size()) throw GeoAlgoException("Trajectory object not properly set...");
528 
529  // Check dimensionality compatibility between point and trajectory
530  trj.compat(pt);
531 
532  // Now keep track of smallest distance and loop over traj segments
533  double distMin = kINVALID_DOUBLE;
534  for (size_t l = 0; l < trj.size() - 1; l++) {
535  double distTmp = _SqDist_(pt, trj[l], trj[l + 1]);
536  if (distTmp < distMin) { distMin = distTmp; }
537  }
538 
539  return distMin;
540  }
541 
542  // Distance between vector of Trajectories and a Point
543  // Loop over Trajectories and find the closest one
544  // then keep track of that closest one
545  double GeoAlgo::SqDist(const Point_t& pt,
546  const std::vector<Trajectory_t>& trj,
547  int& trackIdx) const
548  {
549 
550  // holder for shortest distance
551  double minDist = kINVALID_DOUBLE;
552 
553  // loop over trajectories
554  for (size_t t = 0; t < trj.size(); t++) {
555 
556  // trajectory & point dimensionality will be checked in next function
557  // now calculate distance w.r.t. this track
558  double tmpDist = SqDist(pt, trj[t]);
559  if (tmpDist < minDist) {
560  minDist = tmpDist;
561  trackIdx = t;
562  }
563  } // for all tracks
564 
565  return minDist;
566  }
567 
568  // Closest point between a Trajectory and a Point
569  // Loop over segments that make up the trajectory and keep track
570  // of shortest distance between any of them and the point
571  // For the shortest distance find the point at which it is found
572  Point_t GeoAlgo::ClosestPt(const Point_t& pt, const Trajectory_t& trj, int& idx) const
573  {
574 
575  // Make sure trajectory object is properly defined
576  if (!trj.size()) throw GeoAlgoException("Trajectory object not properly set...");
577 
578  // Check dimensionality compatibility between point and trajectory
579  trj.compat(pt);
580 
581  // Now keep track of smallest distance and loop over traj segments
582  double distMin = kINVALID_DOUBLE;
583  // For that smallest distance, keep track of the segment for which it was found
584  for (size_t l = 0; l < trj.size() - 1; l++) {
585  double distTmp = _SqDist_(pt, trj[l], trj[l + 1]);
586  if (distTmp < distMin) {
587  distMin = distTmp;
588  idx = l;
589  }
590  }
591 
592  // Now that we have the segment for the closest approach
593  // Use it to find the closest point on that segment
594  LineSegment_t segMin(trj[idx], trj[idx + 1]);
595  return _ClosestPt_(pt, segMin);
596  }
597 
598  // Closest point between a vector of trajectories and a point
599  // Loop over segments that make up the trajectory and keep track
600  // of shortest distance between any of them and the point
601  // For the shortest distance find the point at which it is found
603  const std::vector<Trajectory_t>& trj,
604  int& TrackIdx) const
605  {
606 
607  // since finding the smallest distance is faster than finding the closest point
608  // first loop through tracks, and find the one that is closest to the point
609  // then finally find the closest point on that track
610 
611  for (size_t t = 0; t < trj.size(); t++) {
612 
613  // holder for smallest distance
614  double minDist = kINVALID_DOUBLE;
615 
616  // track & point dimensionality will be checked per-track by next function
617  // now calculate distance w.r.t. this track
618  double tmpDist = SqDist(pt, trj[t]);
619  if (tmpDist < minDist) {
620  minDist = tmpDist;
621  TrackIdx = t;
622  }
623 
624  } // for all tracks
625 
626  // now we know which track is closest -> find the closest point to that track
627  return ClosestPt(pt, trj[TrackIdx]);
628  }
629 
630  // Closest Approach between a segment and a Trajectory
631  // loop over segments in trajectory and find the one that
632  // is closest. Then find distance
633  double GeoAlgo::SqDist(const LineSegment_t& seg,
634  const Trajectory_t& trj,
635  Point_t& c1,
636  Point_t& c2) const
637  {
638 
639  // Make sure trajectory object is properly defined
640  if (!trj.size()) throw GeoAlgoException("Trajectory object not properly set...");
641 
642  // Check dimensionality compatibility between point and trajectory
643  trj.compat(seg.Start());
644 
645  // keep track of c1 & c2
646  Point_t c1min;
647  Point_t c2min;
648  // Now keep track of smallest distance and loop over traj segments
649  double distMin = kMAX_DOUBLE;
650 
651  for (size_t l = 0; l < trj.size() - 1; l++) {
652  LineSegment_t segTmp(trj[l], trj[l + 1]);
653  double distTmp = _SqDist_(segTmp, seg, c1min, c2min);
654  if (distTmp < distMin) {
655  c1 = c1min;
656  c2 = c2min;
657  distMin = distTmp;
658  }
659  } //for all segments in the track
660 
661  return distMin;
662  }
663 
664  // Closest Approach between a Trajectory and a Trajectory
665  // loop over segments in trajectory1 and those in
666  // trahectory2 and find the best point
667  double GeoAlgo::SqDist(const Trajectory_t& trj1,
668  const Trajectory_t& trj2,
669  Point_t& c1,
670  Point_t& c2) const
671  {
672 
673  // Make sure trajectory object is properly defined
674  if (!trj1.size() or !trj2.size())
675  throw GeoAlgoException("Trajectory object not properly set...");
676 
677  // Check dimensionality compatibility between point and trajectory
678  trj1.compat(trj2[0]);
679 
680  // keep track of c1 & c2
681  Point_t c1min;
682  Point_t c2min;
683  // Now keep track of smallest distance and loop over traj segments
684  double distMin = kMAX_DOUBLE;
685 
686  for (size_t l1 = 0; l1 < trj1.size() - 1; l1++) {
687  for (size_t l2 = 0; l2 < trj2.size() - 1; l2++) {
688  LineSegment_t segTmp1(trj1[l1], trj1[l1 + 1]);
689  LineSegment_t segTmp2(trj2[l2], trj2[l2 + 1]);
690  double distTmp = _SqDist_(segTmp1, segTmp2, c1min, c2min);
691  if (distTmp < distMin) {
692  c1 = c1min;
693  c2 = c2min;
694  distMin = distTmp;
695  }
696  } // for segments in trajectory 2
697  } //for all segments in trajectory 1
698 
699  return distMin;
700  }
701 
702  // Closest Approach between a HalfLine and a Trajectory
703  // loop over segments in trajectory and find the one that
704  // is closest. Then find distance
705  double GeoAlgo::SqDist(const HalfLine_t& hline,
706  const Trajectory_t& trj,
707  Point_t& c1,
708  Point_t& c2) const
709  {
710 
711  // Make sure trajectory object is properly defined
712  if (!trj.size()) throw GeoAlgoException("Trajectory object not properly set...");
713 
714  // Check dimensionality compatibility between point and trajectory
715  trj.compat(hline.Start());
716 
717  // keep track of c1 & c2
718  Point_t c1min;
719  Point_t c2min;
720  // Now keep track of smallest distance and loop over traj segments
721  double distMin = kMAX_DOUBLE;
722 
723  for (size_t l = 0; l < trj.size() - 1; l++) {
724  LineSegment_t segTmp(trj[l], trj[l + 1]);
725  double distTmp = _SqDist_(hline, segTmp, c1min, c2min);
726  if (distTmp < distMin) {
727  c1 = c1min;
728  c2 = c2min;
729  distMin = distTmp;
730  }
731  } //for all segments in the track
732 
733  return distMin;
734  }
735 
736  // Closest Approach between a Segment and a vector of tracks
737  // keep track of points of closest approach both on nearest
738  // track as well as on segment
739  // keep track of which track has the point of closest approcah
740  double GeoAlgo::SqDist(const LineSegment& seg,
741  const std::vector<Trajectory_t>& trj,
742  Point_t& c1,
743  Point_t& c2,
744  int& trackIdx) const
745  {
746 
747  // holders to keep track of track with shortest distance
748  double minDist = kMAX_DOUBLE;
749  // holders for points of closest approach
750  Point_t c1min;
751  Point_t c2min;
752 
753  for (size_t t = 0; t < trj.size(); t++) {
754 
755  //need to loop over all tracks and find the one which is closest
756 
757  // dimensionality checks will be done in next function, per track.
758 
759  // now calculate closest approach
760  double tmpDist = SqDist(seg, trj[t], c1min, c2min);
761 
762  // is this the best yet?
763  if (tmpDist < minDist) {
764  minDist = tmpDist;
765  c1 = c1min;
766  c2 = c2min;
767  trackIdx = t;
768  }
769 
770  } // for all tracks in vector
771 
772  return minDist;
773  }
774 
775  // Ref. RTCD Sec. 5.1.9 - pg. 148-150
776  double GeoAlgo::_SqDist_(const LineSegment_t& seg1,
777  const LineSegment_t& seg2,
778  Point_t& c1,
779  Point_t& c2) const
780  {
781 
782  double t1, t2;
783 
784  auto const& s1 = seg1.Start();
785  auto const& s2 = seg2.Start();
786  auto const& e1 = seg1.End();
787  auto const& e2 = seg2.End();
788 
789  auto d1 = e1 - s1;
790  auto d2 = e2 - s2;
791  auto r = s1 - s2;
792 
793  double a = d1.SqLength();
794  double e = d2.SqLength();
795  double f = d2 * r;
796 
797  // check if segment is too short
798  if ((a <= 0) and (e <= 0)) {
799  //both segments are too short
800  t1 = t2 = 0.;
801  c1 = s1;
802  c2 = s2;
803  Vector_t distVector = c2 - c1;
804  return distVector.SqLength();
805  }
806  if (a <= 0) {
807  //first segment degenerates into a point
808  t1 = 0.;
809  t2 = f / e;
810  t2 = _Clamp_(t2, 0., 1.);
811  }
812  else {
813  double c = d1 * r;
814  if (e <= 0) {
815  //second segment degenerates into a point
816  t2 = 0.;
817  t1 = _Clamp_(-c / a, 0., 1.);
818  }
819  else {
820  // the general case...no degeneracies
821  double b = d1 * d2;
822  double denom = (a * e) - (b * b);
823 
824  if (denom != 0.)
825  t1 = _Clamp_((b * f - c * e) / denom, 0., 1.);
826  else
827  t1 = 0.;
828 
829  t2 = (b * t1 + f) / e;
830 
831  if (t2 < 0.) {
832  t2 = 0.;
833  t1 = _Clamp_(-c / a, 0., 1.);
834  }
835  else if (t2 > 1.) {
836  t2 = 1.;
837  t1 = _Clamp_((b - c) / a, 0., 1.);
838  }
839  }
840  }
841 
842  c1 = s1 + d1 * t1;
843  c2 = s2 + d2 * t2;
844 
845  Vector_t distVector = c2 - c1;
846  return distVector.SqLength();
847  }
848 
849  // Clamp function:
850  // if 1st argument out of bounds w.r.t. min & max
851  // return the boundary point
852  double GeoAlgo::_Clamp_(const double n, const double min, const double max) const
853  {
854  if (n < min) { return min; }
855  if (n > max) { return max; }
856  return n;
857  }
858 
860  double GeoAlgo::_commonOrigin_(const Line_t& lin1, const Line_t& lin2, Point_t& origin) const
861  {
862 
863  // Function Description:
864  // Given two HalfLine objects, project them backwards
865  // and find the point of closest approach on both
866  // lines.
867  // The half-point between these two is considered the
868  // candidate origin or vertex of the two lines
869  // Then make segments uniting this vertex and
870  // the start point of both half lines.
871  // Take the dot product of the segment uniting
872  // the vertex with the start of lin1, and the direction
873  // of lin1. Similarly for lin2.
874  // These dot-products will be close to 1 if the lines,
875  // traced backwards, indeed point to the reconstructed
876  // vertex.
877  // return the sum of these dot products, which
878  // is bound between -2 and +2.
879  // other values of this return (1, 0, -1, -2)
880  // will give insight on other possible topologies.
881 
882  // get directions of two lines
883  Vector_t dir1(lin1.Pt2() - lin1.Pt1());
884  Vector_t dir2(lin2.Pt2() - lin2.Pt1());
885  dir1.Normalize();
886  dir2.Normalize();
887 
888  // Closest approach points on the two lines
889  Point_t pt1(lin1.Pt1().size());
890  Point_t pt2(lin2.Pt1().size());
891 
892  //double IP = _SqDist_(lin1, lin2, pt1, pt2);
893  origin = (pt1 + pt2) / 2.;
894 
895  // If origin coincides with lin1 start
896  // -> vec1 should be in same direction of lin1
897  Vector_t vec1(dir1);
898  if (lin1.Pt1() != origin) vec1 = lin1.Pt1() - origin;
899  vec1.Normalize();
900  // similarly for vec1
901  Vector_t vec2(dir2);
902  if (lin2.Pt1() != origin) vec2 = lin2.Pt1() - origin;
903  vec2.Normalize();
904 
905  return vec1.Dot(dir1) + vec2.Dot(dir2);
906  }
907 
910  const HalfLine_t& lin2,
911  Point_t& origin,
912  bool backwards) const
913  {
914 
915  //If backwards is false, call infinite line function, otherwise proceed
916  if (!backwards) {
917  Line_t l1(lin1.Start(), lin1.Start() + lin1.Dir());
918  Line_t l2(lin2.Start(), lin2.Start() + lin2.Dir());
919  return _commonOrigin_(l1, l2, origin);
920  }
921 
922  // Function Description:
923  // Given two HalfLine objects, project them backwards
924  // and find the point of closest approach on both
925  // lines.
926  // The half-point between these two is considered the
927  // candidate origin or vertex of the two lines
928  // Then make segments uniting this vertex and
929  // the start point of both half lines.
930  // Take the dot product of the segment uniting
931  // the vertex with the start of lin1, and the direction
932  // of lin1. Similarly for lin2.
933  // These dot-products will be close to 1 if the lines,
934  // traced backwards, indeed point to the reconstructed
935  // vertex.
936  // return the sum of these dot products, which
937  // is bound between -2 and +2.
938  // other values of this return (1, 0, -1, -2)
939  // will give insight on other possible topologies.
940 
941  // Flip the HalfLines: want to project backwards
942  HalfLine_t lin1Back(lin1.Start(), lin1.Dir() * (-1));
943  HalfLine_t lin2Back(lin2.Start(), lin2.Dir() * (-1));
944  // Closest approach points on the two lines
945  Point_t pt1(lin1.Start().size());
946  Point_t pt2(lin2.Start().size());
947 
948  // double IP = _SqDist_(lin1Back, lin2Back, pt1, pt2); Unused variable
949  origin = (pt1 + pt2) / 2.;
950 
951  // If origin coincides with lin1 start
952  // -> vec1 should be in same direction of lin1
953  Vector_t vec1(lin1.Dir());
954  if (lin1.Start() != origin) vec1 = lin1.Start() - origin;
955  vec1.Normalize();
956  // similarly for vec1
957  Vector_t vec2(lin2.Dir());
958  if (lin2.Start() != origin) vec2 = lin2.Start() - origin;
959  vec2.Normalize();
960 
961  return vec1.Dot(lin1.Dir()) + vec2.Dot(lin2.Dir());
962  // std::cout << "dot is: " << dot << std::endl;
963  // if ( !((dot <= 2) && (dot >= -2)) )
964  // throw GeoAlgoException("commonOrigin failed. Sum of two dot-products must be bound by [-2,2]");
965 
966  // return dot;
967  }
970  const LineSegment_t& seg,
971  Point_t& origin,
972  bool backwards) const
973  {
974  // Make a Half-line out of the line-segment
975  // we want to project backwards to a common origin
976  // not limit ourselves to an origin that must be on the segment
977  HalfLine_t lin2(seg.Start(), seg.Dir());
978  return _commonOrigin_(lin, lin2, origin, backwards);
979  }
982  const LineSegment_t& seg2,
983  Point_t& origin,
984  bool backwards) const
985  {
986  // Make a Half-line out of the line-segments
987  // we want to project backwards to a common origin
988  // not limit ourselves to an origin that must be on the segment
989  HalfLine_t lin1(seg1.Start(), seg1.Dir());
990  HalfLine_t lin2(seg2.Start(), seg2.Dir());
991  return _commonOrigin_(lin1, lin2, origin, backwards);
992  }
993 
996  const Trajectory_t& trj2,
997  Point_t& origin,
998  bool backwards) const
999  {
1000  // Turn the trajectory into half-line that connect start -> end
1001  HalfLine_t lin1(trj1.front(), trj1.back() - trj1.front());
1002  // Turn the segment into half-line
1003  HalfLine_t lin2(trj2.front(), trj2.back() - trj2.front());
1004  return _commonOrigin_(lin1, lin2, origin, backwards);
1005  }
1006 
1009  const LineSegment_t& seg,
1010  Point_t& origin,
1011  bool backwards) const
1012  {
1013  // Turn the trajectory into half-line that connect start -> end
1014  HalfLine_t lin1(trj.front(), trj.back() - trj.front());
1015  // Turn the segment into half-line
1016  HalfLine_t lin2(seg.Start(), seg.Dir());
1017  return _commonOrigin_(lin1, lin2, origin, backwards);
1018  }
1019 
1022  const HalfLine_t& lin,
1023  Point_t& origin,
1024  bool backwards) const
1025  {
1026  // Turn the trajectory into half-line that connect start -> end
1027  HalfLine_t lin2(trj.front(), trj.back() - trj.front());
1028  return _commonOrigin_(lin, lin2, origin, backwards);
1029  }
1030 
1033  Sphere_t GeoAlgo::_boundingSphere_(const std::vector<Point_t>& pts) const
1034  {
1035 
1036  // Remove any duplicate points
1037  std::vector<Point_t> copyPts = {pts[0]};
1038  for (size_t p1 = 0; p1 < pts.size(); p1++) {
1039  // if an identical point does not already exist in copyPts -> then add
1040  bool found = false;
1041  for (size_t p2 = 0; p2 < copyPts.size(); p2++)
1042  if (pts[p1] == copyPts[p2]) {
1043  found = true;
1044  break;
1045  }
1046  if (!found) copyPts.push_back(pts[p1]);
1047  }
1048 
1049  // if 4 or less points call appropriate constructor
1050  if (copyPts.size() < 5) return Sphere_t(copyPts);
1051 
1052  size_t npoints = copyPts.size();
1053  std::vector<Point_t> points4 = {
1054  copyPts[npoints - 1], copyPts[npoints - 2], copyPts[npoints - 3], copyPts[npoints - 4]};
1055  copyPts.pop_back();
1056  copyPts.pop_back();
1057  copyPts.pop_back();
1058  copyPts.pop_back();
1059  Sphere_t tmpSphere = Sphere(points4);
1060  return _RemainingPoints_(copyPts, tmpSphere);
1061 
1062  // too many points to call simple constructor! find minimally bounding sphere
1063  // compute sphere for first 4 points
1064  //Sphere_t tmpSphere(copyPts[0],copyPts[1],copyPts[2],copyPts[3]);
1065  //std::vector<Point_t> sosPoints;// = {pts[0]};
1066  //sosPoints.clear();
1067  //return _WelzlSphere_(copyPts,copyPts.size(),sosPoints);
1068  }
1069 
1070  Sphere_t GeoAlgo::_RemainingPoints_(std::vector<Point_t>& remaining,
1071  const Sphere_t& thisSphere) const
1072  {
1073 
1074  // if no points lef -> done...return the current sphere
1075  if (remaining.size() == 0) return thisSphere;
1076 
1077  //std::cout << "Remaining points: " << remaining.size() << std::endl;
1078 
1079  auto const& lastPoint = remaining.back();
1080 
1081  // if this point is bounded by the already constructed sphere, continue
1082  if (thisSphere.Contain(lastPoint)) {
1083  remaining.pop_back();
1084  return _RemainingPoints_(remaining, thisSphere);
1085  }
1086  // if not, need to adjust so that the new point is also bound
1087  // get distance from lastPoint and center
1088  double dist = lastPoint.Dist(thisSphere.Center());
1089  //std::cout << "point does not fit: " << lastPoint << std::endl;
1090  //std::cout << "distance: " << dist << std::endl;
1091  //std::cout << "center : " << thisSphere.Center() << std::endl;
1092  //std::cout << "radius : " << thisSphere.Radius() << std::endl;
1093  // the new center should be shifted in the direction
1094  // of the new point by half the difference between
1095  // the current radius and "dist"
1096  // direction in which to move:
1097  Vector_t dir = lastPoint - thisSphere.Center();
1098  dir.Normalize();
1099  // amount to move by
1100  double shift = (dist - thisSphere.Radius()) / 2.;
1101  if (shift < 0) { shift *= -1; }
1102  Point_t newCenter = thisSphere.Center() + dir * shift;
1103  double newRadius = thisSphere.Radius() + shift;
1104  //std::cout << "new center: " << newCenter << std::endl;
1105  //std::cout << "new radius: " << newRadius << std::endl;
1106  Sphere_t newsphere(newCenter, newRadius);
1107  //if (newsphere.Contain(lastPoint)) { std::cout << "new point contained!" << std::endl; }
1108  //else { std::cout << "WRONG!" << std::endl; }
1109  remaining.pop_back();
1110 
1111  return _RemainingPoints_(remaining, newsphere);
1112  }
1113 
1114  Sphere_t GeoAlgo::_WelzlSphere_(const std::vector<Point_t>& pts,
1115  int numPts,
1116  std::vector<Point_t> sosPts) const
1117  {
1118 
1119  if (numPts == 0) return Sphere_t(sosPts);
1120  // choose last point in the input set as the one to test (if it fits in current sphere or not)
1121  int index = numPts - 1;
1122  // recursively compute the smallest bounding sphere of the remaining points
1123  Sphere_t smallestSphere = _WelzlSphere_(pts, numPts - 1, sosPts);
1124  // if the selected point lies inside this sphere, it is indeed the smallest
1125  if (smallestSphere.Contain(pts[index])) return smallestSphere;
1126  // otherwise, update the set-of-support to additionally contain the new point
1127  sosPts.push_back(pts[index]);
1128  return _WelzlSphere_(pts, numPts - 1, sosPts);
1129  }
1130 
1131 }
TRandom r
Definition: spectrum.C:23
bool Contain(const Point_t &p) const
Judge if a point is contained within a sphere.
Definition: GeoSphere.cxx:365
Point_t ClosestPt(const Line_t &line, const Point_t &pt) const
Definition: GeoAlgo.h:106
double _SqDist_(const Line_t &l1, const Line_t &l2, Point_t &L1, Point_t &L2) const
Line & Line distance w/o dimensionality check.
Definition: GeoAlgo.cxx:193
const Point_t & Start() const
Start getter.
Definition: GeoHalfLine.cxx:28
TTree * t1
Definition: plottest35.C:26
double _Clamp_(const double n, const double min, const double max) const
Clamp function: checks if value out of bounds.
Definition: GeoAlgo.cxx:852
void compat(const Point_t &obj) const
Dimensionality check function w/ Trajectory.
double SqDist(const Line_t &line, const Point_t &pt) const
Definition: GeoAlgo.h:98
Class def header for a class GeoAlgoException.
Representation of a simple 3D line segment Defines a finite 3D straight line by having the start and ...
Representation of a 3D rectangular box which sides are aligned w/ coordinate axis. A representation of an Axis-Aligned-Boundary-Box, a simple & popular representation of 3D boundary box for collision detection. The concept was taken from the reference, Real-Time-Collision-Detection (RTCD), and in particular Ch. 4.2 (page 77): .
Definition: GeoAABox.h:34
double _SqDist_(const Vector &obj) const
Compute the squared-distance to another vector w/o dimension check.
Definition: GeoVector.cxx:138
const Point_t & Pt2() const
Direction getter.
Definition: GeoLine.cxx:28
const Vector_t Dir() const
Direction getter.
const Point_t & Min() const
Minimum point getter.
Definition: GeoAABox.cxx:23
void Normalize()
Normalize itself.
Definition: GeoVector.cxx:116
double SqLength() const
Compute the squared length of the vector.
Definition: GeoVector.cxx:49
TFile f
Definition: plotHisto.C:6
double Length() const
Compute the length of the vector.
Definition: GeoVector.cxx:57
TCanvas * c1
Definition: plotHisto.C:7
LineSegment LineSegment_t
double Dot(const Vector &obj) const
Definition: GeoVector.cxx:73
TText * pt2
Definition: plot.C:64
TCanvas * c2
Definition: plot_hist.C:75
bool Contain(const Point_t &pt) const
Test if a point is contained within the box.
Definition: GeoAABox.cxx:45
static const double kMAX_DOUBLE
bool IsValid() const
Check if point is valid.
Definition: GeoVector.cxx:37
const Point_t & Pt1() const
Start getter.
Definition: GeoLine.cxx:24
const Point_t & End() const
End getter.
TMarker * pt
Definition: egs.C:25
Float_t d
Definition: plot.C:235
Representation of a 3D infinite line. Defines an infinite 3D line by having 2 points which completely...
Definition: GeoLine.h:27
double Radius() const
Radius getter.
Definition: GeoSphere.cxx:341
Sphere_t _WelzlSphere_(const std::vector< Point_t > &pts, int numPts, std::vector< Point_t > sosPts) const
Definition: GeoAlgo.cxx:1114
const Vector_t & Dir() const
Direction getter.
Definition: GeoHalfLine.cxx:33
const Point_t & Center() const
Center getter.
Definition: GeoSphere.cxx:336
const Point_t & Start() const
Start getter.
Sphere_t _boundingSphere_(const std::vector< Point_t > &pts) const
Definition: GeoAlgo.cxx:1033
TTree * t2
Definition: plottest35.C:36
Representation of a 3D semi-infinite line. Defines a semi-infinite 3D line by having a start point (P...
Definition: GeoHalfLine.h:30
TDirectory * dir
Definition: macro.C:5
constexpr double dist(const TReal *x, const TReal *y, const unsigned int dimension)
Sphere_t _RemainingPoints_(std::vector< Point_t > &remaining, const Sphere_t &thisSphere) const
Definition: GeoAlgo.cxx:1070
Class def header for a class GeoAlgo.
const Point_t & Max() const
Maximum point getter.
Definition: GeoAABox.cxx:27
Vector Vector_t
Point has same feature as Vector.
Definition: GeoVector.h:203
LineSegment_t BoxOverlap(const AABox_t &box, const HalfLine_t &line) const
LineSegment sub-segment of HalfLine inside an AABox.
Definition: GeoAlgo.cxx:168
Char_t n[5]
TText * pt1
Definition: plot.C:61
static const double kINVALID_DOUBLE
Float_t e
Definition: plot.C:35
std::vector< Point_t > Intersection(const AABox_t &box, const HalfLine_t &line, bool back=false) const
Intersection between a HalfLine and an AABox.
Definition: GeoAlgo.cxx:11
double _commonOrigin_(const Line_t &lin1, const Line_t &lin2, Point_t &origin) const
Common origin: Line & Line. Keep track of origin.
Definition: GeoAlgo.cxx:860
Sphere Sphere_t
Definition: GeoSphere.h:126
constexpr Point origin()
Returns a origin position with a point of the specified type.
Definition: geo_vectors.h:229
Point_t _ClosestPt_(const Point_t &pt, const LineSegment_t &line) const
Definition: GeoAlgo.cxx:390