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 | = | Struct.new(:id, :coords, :left, :right) |
Public Class methods
Points is a hash of id => [coord, coord] pairs.
# File lib/containers/kd_tree.rb, line 30 def initialize(points) raise "must pass in a hash" unless points.kind_of?(Hash) @dimensions = points[ points.keys.first ].size @root = build_tree(points.to_a) @nearest = [] end
Public Instance methods
Find k closest points to given coordinates
# File lib/containers/kd_tree.rb, line 38 def find_nearest(target, k_nearest) @nearest = [] nearest(@root, target, k_nearest, 0) end