365tuwe

distance.py

Aug 9th, 2013
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. def pointPointDistance(p1, p2):
  2.     '''
  3.        point-to-point distance
  4.        @param p1: first point as tuple
  5.        @param p2: second point as tuple
  6.        @return distance between two points as float
  7.    '''
  8.     return sum((a - b) ** 2 for a, b in zip(p1, p2)) ** 0.5
  9.  
  10.  
  11. def pointLineDistance3D(p, seg, testSegmentEnds=False):
  12.     '''
  13.        minimum distance between a point and a line in 3D
  14.        @param p: point
  15.        @param seg: tuple of two points defining a line
  16.        @return: tuple of minimum distance and projection of p on seg
  17.    '''
  18.     # assign passed tuples to coordinates
  19.     x3, y3, z3 = p
  20.     (x1, y1, z1), (x2, y2, z2) = seg
  21.  
  22.     # distance between line end points in each direction
  23.     dx21 = x2 - x1
  24.     dy21 = y2 - y1
  25.     dz21 = z2 - z1
  26.  
  27.     # square of line length
  28.     lensq21 = dx21 ** 2 + dy21 ** 2 + dz21 ** 2
  29.     if lensq21 is 0:
  30.         # we have a point!
  31.         return None, pointPointDistance((x2, y2, z2), (x3, y3, z3))
  32.  
  33.     # projection of X3X1 on X2X1, normalized with length of X2X1
  34.     u = (x3 - x1) * dx21 + (y3 - y1) * dy21 + (z3 - z1) * dz21
  35.     u /= float(lensq21)
  36.  
  37.     # calculate projection of X3 on X2X1
  38.     x = x1 + u * dx21
  39.     y = y1 + u * dy21
  40.     z = z1 + u * dz21
  41.  
  42.     if testSegmentEnds:
  43.         if u < 0:
  44.             x, y, z = x1, y1, z1
  45.         elif u > 1:
  46.             x, y, z = x2, y2, z2
  47.  
  48.     dx30 = x3 - x
  49.     dy30 = y3 - y
  50.     dz30 = z3 - z
  51.  
  52.     return (x, y, z), (dx30 ** 2 + dy30 ** 2 + dz30 ** 2) ** 0.5
Advertisement
Add Comment
Please, Sign In to add comment