-
Notifications
You must be signed in to change notification settings - Fork 50
/
kdtree.h
303 lines (240 loc) · 6.89 KB
/
kdtree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#ifndef __KDTREE_H__
#define __KDTREE_H__
#include <vector>
#include <numeric>
#include <algorithm>
#include <exception>
#include <functional>
namespace kdt
{
/** @brief k-d tree class.
*/
template <class PointT>
class KDTree
{
public:
/** @brief The constructors.
*/
KDTree() : root_(nullptr) {};
KDTree(const std::vector<PointT>& points) : root_(nullptr) { build(points); }
/** @brief The destructor.
*/
~KDTree() { clear(); }
/** @brief Re-builds k-d tree.
*/
void build(const std::vector<PointT>& points)
{
clear();
points_ = points;
std::vector<int> indices(points.size());
std::iota(std::begin(indices), std::end(indices), 0);
root_ = buildRecursive(indices.data(), (int)points.size(), 0);
}
/** @brief Clears k-d tree.
*/
void clear()
{
clearRecursive(root_);
root_ = nullptr;
points_.clear();
}
/** @brief Validates k-d tree.
*/
bool validate() const
{
try
{
validateRecursive(root_, 0);
}
catch (const Exception&)
{
return false;
}
return true;
}
/** @brief Searches the nearest neighbor.
*/
int nnSearch(const PointT& query, double* minDist = nullptr) const
{
int guess;
double _minDist = std::numeric_limits<double>::max();
nnSearchRecursive(query, root_, &guess, &_minDist);
if (minDist)
*minDist = _minDist;
return guess;
}
/** @brief Searches k-nearest neighbors.
*/
std::vector<int> knnSearch(const PointT& query, int k) const
{
KnnQueue queue(k);
knnSearchRecursive(query, root_, queue, k);
std::vector<int> indices(queue.size());
for (size_t i = 0; i < queue.size(); i++)
indices[i] = queue[i].second;
return indices;
}
/** @brief Searches neighbors within radius.
*/
std::vector<int> radiusSearch(const PointT& query, double radius) const
{
std::vector<int> indices;
radiusSearchRecursive(query, root_, indices, radius);
return indices;
}
private:
/** @brief k-d tree node.
*/
struct Node
{
int idx; //!< index to the original point
Node* next[2]; //!< pointers to the child nodes
int axis; //!< dimension's axis
Node() : idx(-1), axis(-1) { next[0] = next[1] = nullptr; }
};
/** @brief k-d tree exception.
*/
class Exception : public std::exception { using std::exception::exception; };
/** @brief Bounded priority queue.
*/
template <class T, class Compare = std::less<T>>
class BoundedPriorityQueue
{
public:
BoundedPriorityQueue() = delete;
BoundedPriorityQueue(size_t bound) : bound_(bound) { elements_.reserve(bound + 1); };
void push(const T& val)
{
auto it = std::find_if(std::begin(elements_), std::end(elements_),
[&](const T& element){ return Compare()(val, element); });
elements_.insert(it, val);
if (elements_.size() > bound_)
elements_.resize(bound_);
}
const T& back() const { return elements_.back(); };
const T& operator[](size_t index) const { return elements_[index]; }
size_t size() const { return elements_.size(); }
private:
size_t bound_;
std::vector<T> elements_;
};
/** @brief Priority queue of <distance, index> pair.
*/
using KnnQueue = BoundedPriorityQueue<std::pair<double, int>>;
/** @brief Builds k-d tree recursively.
*/
Node* buildRecursive(int* indices, int npoints, int depth)
{
if (npoints <= 0)
return nullptr;
const int axis = depth % PointT::DIM;
const int mid = (npoints - 1) / 2;
std::nth_element(indices, indices + mid, indices + npoints, [&](int lhs, int rhs)
{
return points_[lhs][axis] < points_[rhs][axis];
});
Node* node = new Node();
node->idx = indices[mid];
node->axis = axis;
node->next[0] = buildRecursive(indices, mid, depth + 1);
node->next[1] = buildRecursive(indices + mid + 1, npoints - mid - 1, depth + 1);
return node;
}
/** @brief Clears k-d tree recursively.
*/
void clearRecursive(Node* node)
{
if (node == nullptr)
return;
if (node->next[0])
clearRecursive(node->next[0]);
if (node->next[1])
clearRecursive(node->next[1]);
delete node;
}
/** @brief Validates k-d tree recursively.
*/
void validateRecursive(const Node* node, int depth) const
{
if (node == nullptr)
return;
const int axis = node->axis;
const Node* node0 = node->next[0];
const Node* node1 = node->next[1];
if (node0 && node1)
{
if (points_[node->idx][axis] < points_[node0->idx][axis])
throw Exception();
if (points_[node->idx][axis] > points_[node1->idx][axis])
throw Exception();
}
if (node0)
validateRecursive(node0, depth + 1);
if (node1)
validateRecursive(node1, depth + 1);
}
static double distance(const PointT& p, const PointT& q)
{
double dist = 0;
for (size_t i = 0; i < PointT::DIM; i++)
dist += (p[i] - q[i]) * (p[i] - q[i]);
return sqrt(dist);
}
/** @brief Searches the nearest neighbor recursively.
*/
void nnSearchRecursive(const PointT& query, const Node* node, int *guess, double *minDist) const
{
if (node == nullptr)
return;
const PointT& train = points_[node->idx];
const double dist = distance(query, train);
if (dist < *minDist)
{
*minDist = dist;
*guess = node->idx;
}
const int axis = node->axis;
const int dir = query[axis] < train[axis] ? 0 : 1;
nnSearchRecursive(query, node->next[dir], guess, minDist);
const double diff = fabs(query[axis] - train[axis]);
if (diff < *minDist)
nnSearchRecursive(query, node->next[!dir], guess, minDist);
}
/** @brief Searches k-nearest neighbors recursively.
*/
void knnSearchRecursive(const PointT& query, const Node* node, KnnQueue& queue, int k) const
{
if (node == nullptr)
return;
const PointT& train = points_[node->idx];
const double dist = distance(query, train);
queue.push(std::make_pair(dist, node->idx));
const int axis = node->axis;
const int dir = query[axis] < train[axis] ? 0 : 1;
knnSearchRecursive(query, node->next[dir], queue, k);
const double diff = fabs(query[axis] - train[axis]);
if ((int)queue.size() < k || diff < queue.back().first)
knnSearchRecursive(query, node->next[!dir], queue, k);
}
/** @brief Searches neighbors within radius.
*/
void radiusSearchRecursive(const PointT& query, const Node* node, std::vector<int>& indices, double radius) const
{
if (node == nullptr)
return;
const PointT& train = points_[node->idx];
const double dist = distance(query, train);
if (dist < radius)
indices.push_back(node->idx);
const int axis = node->axis;
const int dir = query[axis] < train[axis] ? 0 : 1;
radiusSearchRecursive(query, node->next[dir], indices, radius);
const double diff = fabs(query[axis] - train[axis]);
if (diff < radius)
radiusSearchRecursive(query, node->next[!dir], indices, radius);
}
Node* root_; //!< root node
std::vector<PointT> points_; //!< points
};
} // kdt
#endif // !__KDTREE_H__