Class: Containers::KDTree

Inherits:
Object
  • Object
show all
Defined in:
lib/containers/kd_tree.rb

Overview

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.

Defined Under Namespace

Classes: Node

Instance Method Summary collapse

Constructor Details

#initialize(points) ⇒ KDTree

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



30
31
32
33
34
35
# 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

Instance Method Details

#find_nearest(target, k_nearest) ⇒ Object

Find k closest points to given coordinates



38
39
40
41
# File 'lib/containers/kd_tree.rb', line 38

def find_nearest(target, k_nearest)
  @nearest = []
  nearest(@root, target, k_nearest, 0)
end