Sub topic 6
Nearest-neighbor search with pruning
This chapter assumes you can read the k-d tree build function from the previous chapter. You should also be comfortable with recursion and squared Euclidean distance.
The idea
A nearest-neighbor query asks for the stored point closest to a target point. A linear scan checks every point. A k-d tree can skip whole subtrees, because each node splits space with a plane, and the plane gives a lower bound on how close any point on the other side can be.
The search follows two rules:
- Go down the side of the splitting plane that contains the target first. This is the near side. It quickly produces a good candidate.
- Visit the other side (the far side) only if the splitting plane is closer to the target than the best match found so far. If the plane is farther away than the best match, every point beyond it is farther too.
The code
import math
class Node:
def __init__(self, point, axis, left, right):
self.point = point
self.axis = axis
self.left = left
self.right = right
def build(points, depth=0):
if not points:
return None
k = len(points[0])
axis = depth % k
points = sorted(points, key=lambda p: p[axis])
mid = len(points) // 2
return Node(
points[mid],
axis,
build(points[:mid], depth + 1),
build(points[mid + 1:], depth + 1),
)
def dist2(a, b):
return sum((x - y) ** 2 for x, y in zip(a, b))
def nearest(node, target, best=None):
if node is None:
return best
d2 = dist2(node.point, target)
if best is None or d2 < best[0]:
best = (d2, node.point)
diff = target[node.axis] - node.point[node.axis]
near, far = (node.left, node.right) if diff < 0 else (node.right, node.left)
best = nearest(near, target, best)
if diff * diff < best[0]:
best = nearest(far, target, best)
return best
points = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)]
tree = build(points)
print(nearest(tree, (9, 2))) # (2, (8, 1)): squared distance 2, point (8, 1)The function returns a pair: the best squared distance and the point. It compares squared distances throughout, so it never calls math.sqrt. Take the square root only if you need the real distance.
Tracing the example
The tree has root (7, 2) splitting on x. Its right child is (9, 6) splitting on y, which has the left child (8, 1). The left subtree holds (5, 4), (2, 3) and (4, 7).
For the target (9, 2):
- The root
(7, 2)gives squared distance 4. The target's x is 9, which is greater than 7, so the near side is the right child. (9, 6)gives 16, which does not beat 4. The target's y is 2, below 6, so the near side is its left child.(8, 1)gives 2, which becomes the new best.- Back at the root, the plane
x = 7is 2 units away, sodiff * diffis 4. That is not less than 2, so the whole left subtree is skipped.
The search touched three of the six points. On larger trees the skipped subtrees are much bigger.
Common errors
- Comparing mixed scales.
diffis a plain distance, whilebest[0]is a squared distance. Comparediff * diffwithbest[0], orabs(diff)with a real distance, never one of each. - Checking the far side before searching the near side. The prune test needs a good
best. If you search the far side first, the bound is weak and little is pruned. - Testing the plane before updating
best. The test must use the best value returned from the near search. - Using the splitting point's distance as the bound. The bound is the distance to the plane along one axis, not to the node's point.
Exercise
Suppose the target is (6, 2) in the example tree. At the root (7, 2), the best squared distance after searching the near side is 5. Is the far side searched?
Show answer
The root splits on x, so diff = 6 - 7 = -1 and diff * diff = 1. Since 1 < 5, the plane is closer than the best match, so the far side must be searched. A point there could be closer than 5.