Subversion Repositories gelsvn

Rev

Rev 203 | Rev 330 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
61 jab 1
#ifndef __KDTREE_H
2
#define __KDTREE_H
3
 
4
#include <cmath>
5
#include <iostream>
6
#include <vector>
7
#include <algorithm>
8
#include "CGLA/CGLA.h"
125 jab 9
#include "CGLA/ArithVec.h"
61 jab 10
 
198 bj 11
#if (_MSC_VER >= 1200)
203 jrf 12
#pragma warning (push)
198 bj 13
#pragma warning (disable: 4018)
14
#endif
15
 
61 jab 16
namespace Geometry
17
{
89 jab 18
	/** \brief A classic K-D tree. 
19
 
61 jab 20
			A K-D tree is a good data structure for storing points in space
21
			and for nearest neighbour queries. It is basically a generalized 
22
			binary tree in K dimensions. */
23
	template<class KeyT, class ValT>
24
	class KDTree
25
	{
26
		typedef typename KeyT::ScalarType ScalarType;
27
		typedef KeyT KeyType;
28
		typedef std::vector<KeyT> KeyVectorType;
29
		typedef std::vector<ValT> ValVectorType;
30
 
31
		/// KDNode struct represents node in KD tree
32
		struct KDNode
33
		{
34
			KeyT key;
35
			ValT val;
36
			short dsc;
37
 
38
			KDNode(): dsc(0) {}
39
 
40
			KDNode(const KeyT& _key, const ValT& _val):
41
				key(_key), val(_val), dsc(-1) {}
42
 
43
			ScalarType dist(const KeyType& p) const 
44
			{
45
				KeyType dist_vec = p;
46
				dist_vec  -= key;
47
				return dot(dist_vec, dist_vec);
48
			}
49
		};
50
 
51
		typedef std::vector<KDNode> NodeVecType;
52
		NodeVecType init_nodes;
53
		NodeVecType nodes;
54
		bool is_built;
55
 
56
		/// The greatest depth of KD tree.
57
		int max_depth;
58
 
324 jab 59
		/// The dimension -- K
60
		const int DIM;
61
 
61 jab 62
		/// Total number of elements in tree
63
		int elements;
64
 
65
		/** Comp is a class used for comparing two keys. Comp is constructed
66
				with the discriminator - i.e. the coordinate of the key that is used
67
				for comparing keys - Comp objects are passed to the sort algorithm.*/
68
		class Comp
69
		{
70
			const int dsc;
71
		public:
72
			Comp(int _dsc): dsc(_dsc) {}
73
			bool operator()(const KeyType& k0, const KeyType& k1) const
74
			{
75
				int dim=KeyType::get_dim();
76
				for(int i=0;i<dim;i++)
77
					{
78
						int j=(dsc+i)%dim;
79
						if(k0[j]<k1[j])
80
							return true;
81
						if(k0[j]>k1[j])
82
							return false;
83
					}
84
				return false;
85
			}
86
 
87
			bool operator()(const KDNode& k0, const KDNode& k1) const
88
			{
89
				return (*this)(k0.key,k1.key);
90
			}
91
		};
92
 
93
 
94
		/** Passed a vector of keys, this function will construct an optimal tree.
95
				It is called recursively - second argument is level in tree. */
96
		void optimize(int, int, int, int);
97
 
98
		/** Finde nearest neighbour. */
99
		int closest_point_priv(int, const KeyType&, ScalarType&) const;
100
 
101
 
102
		void in_sphere_priv(int n, 
103
												const KeyType& p, 
104
												const ScalarType& dist,
105
												std::vector<KeyT>& keys,
106
												std::vector<ValT>& vals) const;
107
 
108
		/** Finds the optimal discriminator. There are more ways, but this 
109
				function traverses the vector and finds out what dimension has
110
				the greatest difference between min and max element. That dimension
111
				is used for discriminator */
112
		int opt_disc(int,int) const;
113
 
114
	public:
115
 
116
		/** Build tree from vector of keys passed as argument. */
117
		KDTree():
118
			is_built(false), max_depth(0), DIM(KeyType::get_dim()), elements(0)
119
		{
120
		}
121
 
122
		/** Insert a key value pair into the tree. Note that the tree needs to 
123
				be built - by calling the build function - before you can search. */
124
		void insert(const KeyT& key, const ValT& val)
125
		{
126
			assert(!is_built);
127
			init_nodes.push_back(KDNode(key,val));
128
		}
129
 
130
		/** Build the tree. After this function have been called, it is no longer 
131
				legal to insert elements, but you can perform searches. */
132
		void build()
133
		{
134
			assert(!is_built);
135
			nodes.resize(init_nodes.size()+1);
136
			if(init_nodes.size() > 0)	
137
				optimize(1,0,init_nodes.size(),0);
138
			NodeVecType v(0);
139
			init_nodes.swap(v);
140
			is_built = true;
141
		}
142
 
143
		/** Find the key value pair closest to the key given as first 
144
				argument. The second argument is the maximum search distance.
145
				The final two arguments contain the closest key and its 
146
				associated value upon return. */
324 jab 147
		bool closest_point(const KeyT& p, ScalarType& dist, KeyT&k, ValT&v) const
61 jab 148
		{
149
			assert(is_built);
324 jab 150
			ScalarType max_sq_dist = CGLA::sqr(dist);
61 jab 151
			if(int n = closest_point_priv(1, p, max_sq_dist))
152
				{
153
					k = nodes[n].key;
154
					v = nodes[n].val;
155
					dist = std::sqrt(max_sq_dist);
156
					return true;
157
				}
158
			return false;
159
		}
160
 
161
		/** Find all the elements within a given radius (second argument) of
162
				the key (first argument). The key value pairs inside the sphere are
163
				returned in a pair of vectors passed as the two last arguments. */
164
		int in_sphere(const KeyType& p, 
324 jab 165
									ScalarType dist,
61 jab 166
									std::vector<KeyT>& keys,
167
									std::vector<ValT>& vals) const
168
		{
169
			assert(is_built);
324 jab 170
			ScalarType max_sq_dist = CGLA::sqr(dist);
61 jab 171
			in_sphere_priv(1,p,max_sq_dist,keys,vals);
172
			return keys.size();
173
		}
174
 
175
 
176
	};
177
 
178
	template<class KeyT, class ValT>
179
	int KDTree<KeyT,ValT>::opt_disc(int kvec_beg,  
180
																	int kvec_end) const 
181
	{
182
		KeyType vmin = init_nodes[kvec_beg].key;
183
		KeyType vmax = init_nodes[kvec_beg].key;
184
		for(int i=kvec_beg;i<kvec_end;i++)
185
			{
186
				vmin = CGLA::v_min(vmin,init_nodes[i].key);
187
				vmax = CGLA::v_max(vmax,init_nodes[i].key);
188
			}
189
		int od=0;
190
		KeyType ave_v = vmax-vmin;
191
		for(int i=1;i<KeyType::get_dim();i++)
192
			if(ave_v[i]>ave_v[od]) od = i;
193
		return od;
194
	} 
195
 
196
	template<class KeyT, class ValT>
197
	void KDTree<KeyT,ValT>::optimize(int cur,
198
																	 int kvec_beg,  
199
																	 int kvec_end,  
200
																	 int level)
201
	{
202
		// Assert that we are not inserting beyond capacity.
203
		assert(cur < nodes.size());
204
 
205
		// If there is just a single element, we simply insert.
206
		if(kvec_beg+1==kvec_end) 
207
			{
208
				max_depth  = std::max(level,max_depth);
209
				nodes[cur] = init_nodes[kvec_beg];
210
				nodes[cur].dsc = -1;
211
				return;
212
			}
213
 
214
		// Find the axis that best separates the data.
215
		int disc = opt_disc(kvec_beg, kvec_end);
216
 
217
		// Compute the median element. See my document on how to do this
218
		// www.imm.dtu.dk/~jab/publications.html
219
		int N = kvec_end-kvec_beg;
220
		int M = 1<< (CGLA::two_to_what_power(N));
221
		int R = N-(M-1);
222
		int left_size  = (M-2)/2;
223
		int right_size = (M-2)/2;
224
		if(R < M/2)
225
			{
226
				left_size += R;
227
			}
228
		else
229
			{
230
				left_size += M/2;
231
				right_size += R-M/2;
232
			}
233
 
234
		int median = kvec_beg + left_size;
235
 
236
		// Sort elements but use nth_element (which is cheaper) than
237
		// a sorting algorithm. All elements to the left of the median
238
		// will be smaller than or equal the median. All elements to the right
239
		// will be greater than or equal to the median.
240
		const Comp comp(disc);
241
		std::nth_element(&init_nodes[kvec_beg], 
242
										 &init_nodes[median], 
243
										 &init_nodes[kvec_end], comp);
244
 
245
		// Insert the node in the final data structure.
246
		nodes[cur] = init_nodes[median];
247
		nodes[cur].dsc = disc;
248
 
249
		// Recursively build left and right tree.
250
		if(left_size>0)	
251
			optimize(2*cur, kvec_beg, median,level+1);
252
 
253
		if(right_size>0) 
254
			optimize(2*cur+1, median+1, kvec_end,level+1);
255
	}
256
 
257
	template<class KeyT, class ValT>
258
	int KDTree<KeyT,ValT>::closest_point_priv(int n, const KeyType& p, 
259
																						ScalarType& dist) const
260
	{
261
		int ret_node = 0;
262
		ScalarType this_dist = nodes[n].dist(p);
263
 
264
		if(this_dist<dist)
265
			{
266
				dist = this_dist;
267
				ret_node = n;
268
			}
269
		if(nodes[n].dsc != -1)
270
			{
271
				int dsc         = nodes[n].dsc;
324 jab 272
				ScalarType dsc_dist  = CGLA::sqr(nodes[n].key[dsc]-p[dsc]);
61 jab 273
				bool left_son   = Comp(dsc)(p,nodes[n].key);
274
 
275
				if(left_son||dsc_dist<dist)
276
					{
277
						int left_child = 2*n;
278
						if(left_child < nodes.size())
279
							if(int nl=closest_point_priv(left_child, p, dist))
280
								ret_node = nl;
281
					}
282
				if(!left_son||dsc_dist<dist)
283
					{
284
						int right_child = 2*n+1;
285
						if(right_child < nodes.size())
286
							if(int nr=closest_point_priv(right_child, p, dist))
287
								ret_node = nr;
288
					}
289
			}
290
		return ret_node;
291
	}
292
 
293
	template<class KeyT, class ValT>
294
	void KDTree<KeyT,ValT>::in_sphere_priv(int n, 
295
																				 const KeyType& p, 
296
																				 const ScalarType& dist,
297
																				 std::vector<KeyT>& keys,
298
																				 std::vector<ValT>& vals) const
299
	{
300
		ScalarType this_dist = nodes[n].dist(p);
301
		assert(n<nodes.size());
302
		if(this_dist<dist)
303
			{
304
				keys.push_back(nodes[n].key);
305
				vals.push_back(nodes[n].val);
306
			}
307
		if(nodes[n].dsc != -1)
308
			{
309
				const int dsc         = nodes[n].dsc;
324 jab 310
				const ScalarType dsc_dist  = CGLA::sqr(nodes[n].key[dsc]-p[dsc]);
61 jab 311
 
312
				bool left_son = Comp(dsc)(p,nodes[n].key);
313
 
314
				if(left_son||dsc_dist<dist)
315
					{
316
						int left_child = 2*n;
317
						if(left_child < nodes.size())
318
							in_sphere_priv(left_child, p, dist, keys, vals);
319
					}
320
				if(!left_son||dsc_dist<dist)
321
					{
322
						int right_child = 2*n+1;
323
						if(right_child < nodes.size())
324
							in_sphere_priv(right_child, p, dist, keys, vals);
325
					}
326
			}
327
	}
328
}
329
namespace GEO = Geometry;
330
 
198 bj 331
#if (_MSC_VER >= 1200)
203 jrf 332
#pragma warning (pop)
61 jab 333
#endif
198 bj 334
 
335
 
336
#endif