class Containers::KDTree

A kd-tree is a binary tree that allows one to store points (of any space dimension: 2D, 3D, etc). The structure of the resulting tree makes it so that large portions of the tree are pruned during queries.

One very good use of the tree is to allow nearest neighbor searching. Let’s say you have a number of points in 2D space, and you want to find the nearest 2 points from a specific point:

First, put the points into the tree:

kdtree = Containers::KDTree.new( {0 => [4, 3], 1 => [3, 4], 2 => [-1, 2], 3 => [6, 4],
                                 4 => [3, -5], 5 => [-2, -5] })

Then, query on the tree:

puts kd.find_nearest([0, 0], 2) => [[5, 2], [9, 1]]

The result is an array of [distance, id] pairs. There seems to be a bug in this version.

Note that the point queried on does not have to exist in the tree. However, if it does exist, it will be returned.

Constants

Node

Public Class Methods

new(points) click to toggle source

Points is a hash of id => [coord, coord] pairs.

   # File lib/containers/kd_tree.rb
30 def initialize(points)
31   raise "must pass in a hash" unless points.kind_of?(Hash)
32   @dimensions = points[ points.keys.first ].size
33   @root = build_tree(points.to_a)
34   @nearest = []
35 end

Public Instance Methods

find_nearest(target, k_nearest) click to toggle source

Find k closest points to given coordinates

   # File lib/containers/kd_tree.rb
38 def find_nearest(target, k_nearest)
39   @nearest = []
40   nearest(@root, target, k_nearest, 0)
41 end

Private Instance Methods

build_tree(points, depth=0) click to toggle source

points is an array

   # File lib/containers/kd_tree.rb
44 def build_tree(points, depth=0)
45   return if points.empty?
46   
47   axis = depth % @dimensions
48   
49   points.sort! { |a, b| a.last[axis] <=> b.last[axis] }
50   median = points.size / 2
51   
52   node = Node.new(points[median].first, points[median].last, nil, nil)
53   node.left = build_tree(points[0...median], depth+1)
54   node.right = build_tree(points[median+1..-1], depth+1)
55   node
56 end
check_nearest(nearest, node, target, k_nearest) click to toggle source

Update array of nearest elements if necessary

   # File lib/containers/kd_tree.rb
69 def check_nearest(nearest, node, target, k_nearest)
70   d = distance2(node, target) 
71   if nearest.size < k_nearest || d < nearest.last[0]
72     nearest.pop if nearest.size >= k_nearest
73     nearest << [d, node.id]
74     nearest.sort! { |a, b| a[0] <=> b[0] }
75   end
76   nearest
77 end
distance2(node, target) click to toggle source

Euclidian distanced, squared, between a node and target coords

   # File lib/containers/kd_tree.rb
60 def distance2(node, target)
61   return nil if node.nil? or target.nil?
62   c = (node.coords[0] - target[0])
63   d = (node.coords[1] - target[1])
64   c * c + d * d
65 end
nearest(node, target, k_nearest, depth) click to toggle source

Recursively find nearest coordinates, going down the appropriate branch as needed

    # File lib/containers/kd_tree.rb
 81 def nearest(node, target, k_nearest, depth)
 82   axis = depth % @dimensions
 83 
 84   if node.left.nil? && node.right.nil? # Leaf node
 85     @nearest = check_nearest(@nearest, node, target, k_nearest)
 86     return
 87   end
 88 
 89   # Go down the nearest split
 90   if node.right.nil? || (node.left && target[axis] <= node.coords[axis])
 91     nearer = node.left
 92     further = node.right
 93   else
 94     nearer = node.right
 95     further = node.left
 96   end
 97   nearest(nearer, target, k_nearest, depth+1)
 98 
 99   # See if we have to check other side
100   if further
101     if @nearest.size < k_nearest || (target[axis] - node.coords[axis])**2 < @nearest.last[0]
102       nearest(further, target, k_nearest, depth+1)
103     end
104   end
105 
106   @nearest = check_nearest(@nearest, node, target, k_nearest)
107 end