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