kd-tree 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ bin/*
3
+ -
4
+ features/**/*.feature
5
+ LICENSE.txt
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --color
data/.rvmrc ADDED
@@ -0,0 +1 @@
1
+ rvm use 1.9.2-patched@kdtree
data/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ source "http://rubygems.org"
2
+ # Add dependencies required to use your gem here.
3
+ # Example:
4
+ # gem "activesupport", ">= 2.3.5"
5
+
6
+ # Add dependencies to develop your gem here.
7
+ # Include everything needed to run rake, tests, features, etc.
8
+ group :development do
9
+ gem "rspec", "~> 2.3.0"
10
+ gem "bundler", "~> 1.0.0"
11
+ gem "jeweler", "~> 1.6.4"
12
+ gem "rcov", ">= 0"
13
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,28 @@
1
+ GEM
2
+ remote: http://rubygems.org/
3
+ specs:
4
+ diff-lcs (1.1.3)
5
+ git (1.2.5)
6
+ jeweler (1.6.4)
7
+ bundler (~> 1.0)
8
+ git (>= 1.2.5)
9
+ rake
10
+ rake (0.9.2)
11
+ rcov (0.9.10)
12
+ rspec (2.3.0)
13
+ rspec-core (~> 2.3.0)
14
+ rspec-expectations (~> 2.3.0)
15
+ rspec-mocks (~> 2.3.0)
16
+ rspec-core (2.3.1)
17
+ rspec-expectations (2.3.0)
18
+ diff-lcs (~> 1.1.2)
19
+ rspec-mocks (2.3.0)
20
+
21
+ PLATFORMS
22
+ ruby
23
+
24
+ DEPENDENCIES
25
+ bundler (~> 1.0.0)
26
+ jeweler (~> 1.6.4)
27
+ rcov
28
+ rspec (~> 2.3.0)
data/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2011 Jeremy Holland
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,19 @@
1
+ = kdtree
2
+
3
+ Description goes here.
4
+
5
+ == Contributing to kd-tree
6
+
7
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
8
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
9
+ * Fork the project
10
+ * Start a feature/bugfix branch
11
+ * Commit and push until you are happy with your contribution
12
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
13
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
14
+
15
+ == Copyright
16
+
17
+ Copyright (c) 2011 Jeremy Holland. See LICENSE.txt for
18
+ further details.
19
+
data/Rakefile ADDED
@@ -0,0 +1,49 @@
1
+ # encoding: utf-8
2
+
3
+ require 'rubygems'
4
+ require 'bundler'
5
+ begin
6
+ Bundler.setup(:default, :development)
7
+ rescue Bundler::BundlerError => e
8
+ $stderr.puts e.message
9
+ $stderr.puts "Run `bundle install` to install missing gems"
10
+ exit e.status_code
11
+ end
12
+ require 'rake'
13
+
14
+ require 'jeweler'
15
+ Jeweler::Tasks.new do |gem|
16
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
17
+ gem.name = "kd-tree"
18
+ gem.homepage = "http://github.com/awebneck/kdtree"
19
+ gem.license = "MIT"
20
+ gem.summary = %Q{A pure-ruby kd-tree implementation}
21
+ gem.description = %Q{Great for nearest neighbor search in k dimensions! (as long as k is reasonable)}
22
+ gem.email = "jeremy@jeremypholland.com"
23
+ gem.authors = ["Jeremy Holland"]
24
+ # dependencies defined in Gemfile
25
+ end
26
+ Jeweler::RubygemsDotOrgTasks.new
27
+
28
+ require 'rspec/core'
29
+ require 'rspec/core/rake_task'
30
+ RSpec::Core::RakeTask.new(:spec) do |spec|
31
+ spec.pattern = FileList['spec/**/*_spec.rb']
32
+ end
33
+
34
+ RSpec::Core::RakeTask.new(:rcov) do |spec|
35
+ spec.pattern = 'spec/**/*_spec.rb'
36
+ spec.rcov = true
37
+ end
38
+
39
+ task :default => :spec
40
+
41
+ require 'rake/rdoctask'
42
+ Rake::RDocTask.new do |rdoc|
43
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
44
+
45
+ rdoc.rdoc_dir = 'rdoc'
46
+ rdoc.title = "kd-tree #{version}"
47
+ rdoc.rdoc_files.include('README*')
48
+ rdoc.rdoc_files.include('lib/**/*.rb')
49
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.0.3
data/kd-tree.gemspec ADDED
@@ -0,0 +1,64 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = "kd-tree"
8
+ s.version = "0.0.3"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Jeremy Holland"]
12
+ s.date = "2011-10-04"
13
+ s.description = "Great for nearest neighbor search in k dimensions! (as long as k is reasonable)"
14
+ s.email = "jeremy@jeremypholland.com"
15
+ s.extra_rdoc_files = [
16
+ "LICENSE.txt",
17
+ "README.rdoc"
18
+ ]
19
+ s.files = [
20
+ ".document",
21
+ ".rspec",
22
+ ".rvmrc",
23
+ "Gemfile",
24
+ "Gemfile.lock",
25
+ "LICENSE.txt",
26
+ "README.rdoc",
27
+ "Rakefile",
28
+ "VERSION",
29
+ "kd-tree.gemspec",
30
+ "lib/kd-tree.rb",
31
+ "lib/kd_tree.rb",
32
+ "lib/kd_tree/hyper_rect.rb",
33
+ "lib/kd_tree/point.rb",
34
+ "spec/kd_tree_spec.rb",
35
+ "spec/spec_helper.rb"
36
+ ]
37
+ s.homepage = "http://github.com/awebneck/kdtree"
38
+ s.licenses = ["MIT"]
39
+ s.require_paths = ["lib"]
40
+ s.rubygems_version = "1.8.10"
41
+ s.summary = "A pure-ruby kd-tree implementation"
42
+
43
+ if s.respond_to? :specification_version then
44
+ s.specification_version = 3
45
+
46
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
47
+ s.add_development_dependency(%q<rspec>, ["~> 2.3.0"])
48
+ s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
49
+ s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"])
50
+ s.add_development_dependency(%q<rcov>, [">= 0"])
51
+ else
52
+ s.add_dependency(%q<rspec>, ["~> 2.3.0"])
53
+ s.add_dependency(%q<bundler>, ["~> 1.0.0"])
54
+ s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
55
+ s.add_dependency(%q<rcov>, [">= 0"])
56
+ end
57
+ else
58
+ s.add_dependency(%q<rspec>, ["~> 2.3.0"])
59
+ s.add_dependency(%q<bundler>, ["~> 1.0.0"])
60
+ s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
61
+ s.add_dependency(%q<rcov>, [">= 0"])
62
+ end
63
+ end
64
+
data/lib/kd-tree.rb ADDED
@@ -0,0 +1 @@
1
+ require "#{File.dirname(__FILE__)}/kd_tree"
data/lib/kd_tree.rb ADDED
@@ -0,0 +1,102 @@
1
+ require File.dirname(__FILE__)+'/kd_tree/point'
2
+ require File.dirname(__FILE__)+'/kd_tree/hyper_rect'
3
+
4
+ class KDTree
5
+ attr_accessor :exemplar, :split, :kd_left, :kd_right
6
+
7
+ def initialize(exemplar_set)
8
+ return if exemplar_set.empty?
9
+ exemplar_set = extract_pivot exemplar_set
10
+ split! exemplar_set
11
+ end
12
+
13
+ def extract_pivot(exemplar_set)
14
+ k = exemplar_set[0].length - 1
15
+ max_spread = -Float::INFINITY
16
+ max_spread_o = 0
17
+ max_spread_d = 0
18
+ k.times do |i|
19
+ min = Float::INFINITY
20
+ max = -Float::INFINITY
21
+ exemplar_set.each do |ex|
22
+ min = ex[k] if ex[k] < min
23
+ max = ex[k] if ex[k] > max
24
+ end
25
+ if max - min > max_spread
26
+ max_spread = max - min
27
+ max_spread_o = min
28
+ max_spread_d = i
29
+ end
30
+ end
31
+ @split = max_spread_d
32
+ mid_coord = max_spread_o + (max_spread/2.0)
33
+ split_d_coords = exemplar_set.map do |ex|
34
+ ex[split]
35
+ end
36
+ mid_closest_coord = Float::INFINITY
37
+ mid_closest_index = 0
38
+ split_d_coords.each_with_index do |coord, i|
39
+ if (coord - mid_coord).abs < mid_closest_coord
40
+ mid_closest_coord = coord
41
+ mid_closest_index = i
42
+ end
43
+ end
44
+ @exemplar = exemplar_set.delete_at mid_closest_index
45
+ exemplar_set
46
+ end
47
+
48
+ def split!(exemplar_set)
49
+ left_set = []
50
+ right_set = []
51
+ exemplar_set.each do |ex|
52
+ if ex[@split] <= @exemplar[@split]
53
+ left_set << ex
54
+ else
55
+ right_set << ex
56
+ end
57
+ end
58
+ @kd_left = self.class.new left_set
59
+ @kd_right = self.class.new right_set
60
+ end
61
+
62
+ def nearest_neighbor(target, metric=:euclidean)
63
+ nearest_neighbors(target, 1, metric)[0]
64
+ end
65
+
66
+ def cut_kspace_by(target, hr)
67
+ hrl, hrr = hr.cut @split, @exemplar[@split]
68
+ if target[@split] <= @exemplar[@split]
69
+ [@kd_left, hrl, @kd_right, hrr]
70
+ else
71
+ [@kd_right, hrr, @kd_left, hrl]
72
+ end
73
+ end
74
+
75
+ def nearest_neighbors(target, n, metric=:euclidean, acc=[], hr=HyperRect.new(target.length), max_dist=Float::INFINITY)
76
+ return acc if @exemplar.nil?
77
+ nearer_kd, nearer_hr, further_kd, further_hr = self.cut_kspace_by target, hr
78
+ acc = nearer_kd.nearest_neighbors target, n, metric, acc, nearer_hr, max_dist
79
+ max_dist = acc.last[:dist] if acc.length == n && acc.last[:dist] < max_dist
80
+ acc = backtrack_check target, n, metric, acc, further_hr, max_dist, further_kd
81
+ acc.sort_by { |node| node[:dist] }
82
+ end
83
+
84
+ def backtrack_check(target, n, metric, acc, hr, max_dist, kd)
85
+ if hr.intersects? target, max_dist, metric
86
+ dist = @exemplar.distance_from(target, metric)
87
+ if acc.length < n || dist < acc.last[:dist]
88
+ acc = acc.clone
89
+ max_dist = dist if acc.length == n
90
+ acc << {:node => @exemplar, :dist => dist}
91
+ acc = acc.sort_by { |node| node[:dist] }
92
+ acc.delete_at n if acc.length > n
93
+ end
94
+ temp_acc = kd.nearest_neighbors target, n, metric, acc, hr, max_dist
95
+ if ((temp_acc.length > 0) && (acc.length < n || temp_acc.last[:dist] < acc.last[:dist]))
96
+ acc = temp_acc
97
+ end
98
+ end
99
+ acc
100
+ end
101
+ end
102
+
@@ -0,0 +1,43 @@
1
+ class KDTree
2
+ class HyperRect
3
+ attr_accessor :minima, :maxima
4
+ def initialize(k)
5
+ @minima = []
6
+ @maxima = []
7
+ k.times do |i|
8
+ @minima << -Float::INFINITY
9
+ @maxima << Float::INFINITY
10
+ end
11
+ end
12
+
13
+ def clone
14
+ cl = self.class.new @minima.length
15
+ cl.minima = @minima.clone
16
+ cl.maxima = @maxima.clone
17
+ cl
18
+ end
19
+
20
+ def cut(dim, pivot)
21
+ left_hr = self.clone
22
+ left_hr.maxima[dim] = pivot
23
+ right_hr = self.clone
24
+ right_hr.minima[dim] = pivot
25
+ [left_hr, right_hr]
26
+ end
27
+
28
+ def intersects?(target, radius, metric)
29
+ near_point = KDTree::Point.new
30
+ target.length.times do |i|
31
+ if target[i] <= @minima[i]
32
+ coord = @minima[i]
33
+ elsif @minima[i] < target[i] && target[i] < @maxima[i]
34
+ coord = target[i]
35
+ else
36
+ coord = @maxima[i]
37
+ end
38
+ near_point[i] = coord
39
+ end
40
+ near_point.distance_from(target, metric) <= radius
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,30 @@
1
+ class KDTree
2
+ class Point < Array
3
+ attr_accessor :data
4
+
5
+ def distance_from(target, metric)
6
+ i = 0
7
+ case metric
8
+ when :euclidean
9
+ self.inject(0) do |acc, el|
10
+ dist = acc + ((el-target[i])**2.0)
11
+ i += 1
12
+ dist
13
+ end
14
+ when :manhattan
15
+ self.inject(0) do |acc, el|
16
+ dist = acc + (el-target[i]).abs
17
+ i += 1
18
+ dist
19
+ end
20
+ when :chebyshev
21
+ self.inject(0) do |acc, el|
22
+ delt = (el-target[i]).abs
23
+ dist = delt > acc ? delt : acc
24
+ i += 1
25
+ dist
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,8 @@
1
+ require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
2
+
3
+ describe KDTree do
4
+ it "should exist" do
5
+ Module.constants.should include :KDTree
6
+ KDTree.should be_a Module
7
+ end
8
+ end
@@ -0,0 +1,12 @@
1
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
2
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
3
+ require 'rspec'
4
+ require 'kd-tree'
5
+
6
+ # Requires supporting files with custom matchers and macros, etc,
7
+ # in ./support/ and its subdirectories.
8
+ Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
9
+
10
+ RSpec.configure do |config|
11
+
12
+ end
metadata ADDED
@@ -0,0 +1,110 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: kd-tree
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.3
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Jeremy Holland
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2011-10-04 00:00:00.000000000Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rspec
16
+ requirement: &2169163600 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: 2.3.0
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: *2169163600
25
+ - !ruby/object:Gem::Dependency
26
+ name: bundler
27
+ requirement: &2169163000 !ruby/object:Gem::Requirement
28
+ none: false
29
+ requirements:
30
+ - - ~>
31
+ - !ruby/object:Gem::Version
32
+ version: 1.0.0
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: *2169163000
36
+ - !ruby/object:Gem::Dependency
37
+ name: jeweler
38
+ requirement: &2169162400 !ruby/object:Gem::Requirement
39
+ none: false
40
+ requirements:
41
+ - - ~>
42
+ - !ruby/object:Gem::Version
43
+ version: 1.6.4
44
+ type: :development
45
+ prerelease: false
46
+ version_requirements: *2169162400
47
+ - !ruby/object:Gem::Dependency
48
+ name: rcov
49
+ requirement: &2169161820 !ruby/object:Gem::Requirement
50
+ none: false
51
+ requirements:
52
+ - - ! '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ type: :development
56
+ prerelease: false
57
+ version_requirements: *2169161820
58
+ description: Great for nearest neighbor search in k dimensions! (as long as k is reasonable)
59
+ email: jeremy@jeremypholland.com
60
+ executables: []
61
+ extensions: []
62
+ extra_rdoc_files:
63
+ - LICENSE.txt
64
+ - README.rdoc
65
+ files:
66
+ - .document
67
+ - .rspec
68
+ - .rvmrc
69
+ - Gemfile
70
+ - Gemfile.lock
71
+ - LICENSE.txt
72
+ - README.rdoc
73
+ - Rakefile
74
+ - VERSION
75
+ - kd-tree.gemspec
76
+ - lib/kd-tree.rb
77
+ - lib/kd_tree.rb
78
+ - lib/kd_tree/hyper_rect.rb
79
+ - lib/kd_tree/point.rb
80
+ - spec/kd_tree_spec.rb
81
+ - spec/spec_helper.rb
82
+ homepage: http://github.com/awebneck/kdtree
83
+ licenses:
84
+ - MIT
85
+ post_install_message:
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ none: false
91
+ requirements:
92
+ - - ! '>='
93
+ - !ruby/object:Gem::Version
94
+ version: '0'
95
+ segments:
96
+ - 0
97
+ hash: 3577641377396895372
98
+ required_rubygems_version: !ruby/object:Gem::Requirement
99
+ none: false
100
+ requirements:
101
+ - - ! '>='
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ requirements: []
105
+ rubyforge_project:
106
+ rubygems_version: 1.8.10
107
+ signing_key:
108
+ specification_version: 3
109
+ summary: A pure-ruby kd-tree implementation
110
+ test_files: []