| Class | Batfish::BKTree |
| In: |
lib/data/bktree.rb
|
| Parent: | Object |
A BK-tree is a datastructure used for nearest neighbor lookup in a metric space. A metric space is any space with the following properties:
To use this datastructure, the objects added to it must have a distance_to(other) class method defined.
| root | [R] |
Add an object to the tree. Returns the tree itself so several adds may be chained together.
# File lib/data/bktree.rb, line 26 def add(obj) if @root @root.add(obj) else @root = Node.new(obj) end return self end
Returns true if the tree is empty.
# File lib/data/bktree.rb, line 37 def empty? return @root.nil? ? true : false end
Returns an array containing all object within threshold distance of the given object. If a block is given, it is called once for each objects within threshold distance of the given object.
# File lib/data/bktree.rb, line 63 def fetch_near(obj, threshold) objs = [] @root.fetch_near(obj, threshold) do |item| yield(item) if block_given? objs << item end return objs end
Returns the nearest object to the given object.
# File lib/data/bktree.rb, line 74 def fetch_nearest(obj) threshold = 0 nearests = [] while nearests.empty? self.fetch_near(obj, threshold) do |item| yield(item) if block_given? nearests << item end threshold += 1 end return nearests end
Returns true if the given object is present in the tree.
# File lib/data/bktree.rb, line 43 def include?(obj) self.include_near?(obj, 0) end
Return true if the given object is within threshold distance of an object in the tree.
# File lib/data/bktree.rb, line 50 def include_near?(obj, threshold) self.fetch_near(obj, threshold) do return true end return false end