knncolle
Collection of KNN methods in C++
Loading...
Searching...
No Matches
Vptree.hpp
Go to the documentation of this file.
1#ifndef KNNCOLLE_VPTREE_HPP
2#define KNNCOLLE_VPTREE_HPP
3
4#include "distances.hpp"
5#include "NeighborQueue.hpp"
6#include "Prebuilt.hpp"
7#include "Builder.hpp"
8#include "Matrix.hpp"
10#include "utils.hpp"
11
12#include <vector>
13#include <random>
14#include <limits>
15#include <memory>
16#include <cstddef>
17#include <string>
18#include <cstring>
19#include <filesystem>
20#include <cassert>
21#include <optional>
22#include <algorithm>
23
24#include "sanisizer/sanisizer.hpp"
25
32namespace knncolle {
33
37inline static constexpr const char* vptree_prebuilt_save_name = "knncolle::Vptree";
38
47 std::optional<typename std::mt19937_64::result_type> seed;
48};
49
53template<typename Index_, typename Data_, typename Distance_, class DistanceMetric_>
54class VptreePrebuilt;
55
56template<typename Index_>
57struct VptreeSearchHistory {
58 VptreeSearchHistory(bool right, Index_ node) : node(node), right(right) {}
59 Index_ node;
60 bool right;
61};
62
63template<typename Index_, typename Data_, typename Distance_, class DistanceMetric_>
64class VptreeSearcher final : public Searcher<Index_, Data_, Distance_> {
65public:
66 VptreeSearcher(const VptreePrebuilt<Index_, Data_, Distance_, DistanceMetric_>& parent) : my_parent(parent) {}
67
68private:
69 const VptreePrebuilt<Index_, Data_, Distance_, DistanceMetric_>& my_parent;
70 NeighborQueue<Index_, Distance_> my_nearest;
71 std::vector<VptreeSearchHistory<Index_> > my_history;
72 std::vector<std::pair<Distance_, Index_> > my_all_neighbors;
73
74public:
75 void search(Index_ i, Index_ k, std::vector<Index_>* output_indices, std::vector<Distance_>* output_distances) {
76 assert(k == 0 || k < my_parent.num_observations());
77 my_nearest.reset(k + 1); // +1 is safe as k < num_obs.
78 auto iptr = my_parent.my_data.data() + sanisizer::product_unsafe<std::size_t>(my_parent.my_new_locations[i], my_parent.my_dim);
79 my_parent.search_nn(iptr, my_nearest, my_history);
80 my_nearest.report(output_indices, output_distances, i);
81 }
82
83 void search(const Data_* query, Index_ k, std::vector<Index_>* output_indices, std::vector<Distance_>* output_distances) {
84 assert(k <= my_parent.num_observations());
85 // Protect the NeighborQueue from k = 0. This also protects search_nn()
86 // when there are no observations (and no node 0 to start recursion).
87 if (k == 0 || my_parent.my_nodes.empty()) {
88 if (output_indices) {
89 output_indices->clear();
90 }
91 if (output_distances) {
92 output_distances->clear();
93 }
94
95 } else {
96 my_nearest.reset(k);
97 my_parent.search_nn(query, my_nearest, my_history);
98 my_nearest.report(output_indices, output_distances);
99 }
100 }
101
102 bool can_search_all() const {
103 return true;
104 }
105
106 Index_ search_all(Index_ i, Distance_ d, std::vector<Index_>* output_indices, std::vector<Distance_>* output_distances) {
107 auto iptr = my_parent.my_data.data() + sanisizer::product_unsafe<std::size_t>(my_parent.my_new_locations[i], my_parent.my_dim);
108
109 if (!output_indices && !output_distances) {
110 Index_ count = 0;
111 my_parent.template search_all<true>(iptr, d, count, my_history);
113
114 } else {
115 my_all_neighbors.clear();
116 my_parent.template search_all<false>(iptr, d, my_all_neighbors, my_history);
117 report_all_neighbors(my_all_neighbors, output_indices, output_distances, i);
118 return count_all_neighbors_without_self(my_all_neighbors.size());
119 }
120 }
121
122 Index_ search_all(const Data_* query, Distance_ d, std::vector<Index_>* output_indices, std::vector<Distance_>* output_distances) {
123 if (my_parent.my_nodes.empty()) { // protect the search_all() method when there is not even a node 0 to start the recursion.
124 my_all_neighbors.clear();
125 report_all_neighbors(my_all_neighbors, output_indices, output_distances);
126 return 0;
127 }
128
129 if (!output_indices && !output_distances) {
130 Index_ count = 0;
131 my_parent.template search_all<true>(query, d, count, my_history);
132 return count;
133
134 } else {
135 my_all_neighbors.clear();
136 my_parent.template search_all<false>(query, d, my_all_neighbors, my_history);
137 report_all_neighbors(my_all_neighbors, output_indices, output_distances);
138 return my_all_neighbors.size();
139 }
140 }
141};
142
143template<typename Index_, typename Data_, typename Distance_, class DistanceMetric_>
144class VptreePrebuilt final : public Prebuilt<Index_, Data_, Distance_> {
145private:
146 std::size_t my_dim;
147 Index_ my_obs;
148 std::vector<Data_> my_data;
149 std::shared_ptr<const DistanceMetric_> my_metric;
150
151public:
152 Index_ num_observations() const {
153 return my_obs;
154 }
155
156 std::size_t num_dimensions() const {
157 return my_dim;
158 }
159
160private:
161 /* Adapted from http://stevehanov.ca/blog/index.php?id=130 */
162
163 // Normally, 'left' or 'right' must be > 0, as the first node in 'nodes' is
164 // the root and cannot be referenced from other nodes. This means that we
165 // can use 0 as a sentinel to indicate that no child exists here.
166 static constexpr Index_ TERMINAL = 0;
167
168 // Single node of a VP tree.
169 struct Node {
170 Distance_ radius = 0;
171
172 // Original index of current vantage point, defining the center of the node.
173 Index_ index = 0;
174
175 // Node index of the next vantage point for all children no more than 'threshold' from the current vantage point.
176 Index_ left = TERMINAL;
177
178 // Node index of the next vantage point for all children no less than 'threshold' from the current vantage point.
179 Index_ right = TERMINAL;
180 };
181
182 std::vector<Node> my_nodes;
183
184 void build(const VptreeOptions& options) {
185 typedef std::pair<Distance_, Index_> DataPoint;
186 std::vector<DataPoint> items;
187 items.reserve(my_obs);
188 for (Index_ i = 0; i < my_obs; ++i) {
189 items.emplace_back(0, i);
190 }
191
192 std::mt19937_64 rng([&]() {
193 if (options.seed.has_value()) {
194 return *(options.seed);
195 }
196
197 // Statistical correctness doesn't matter (aside from tie breaking)
198 // so we'll just use a deterministically 'random' number to ensure
199 // we get the same ties for any given dataset but a different stream
200 // of numbers between datasets. Casting to get well-defined overflow.
201 typedef typename std::mt19937_64::result_type SeedType;
202 const SeedType base = 1234567890, m1 = my_obs, m2 = my_dim;
203 return static_cast<SeedType>(base * m1 + m2);
204 }());
205
206 // We're assuming that lower < upper at each loop. This requires some protection at the call site when nobs = 0, see the constructor.
207 Index_ lower = 0, upper = my_obs;
208
209 // Reserving everything so there there won't be a reallocation, which ensures that pointers to various members will remain valid.
210 my_nodes.reserve(my_obs);
211 const auto coords = my_data.data();
212
213 struct BuildHistory {
214 BuildHistory(Index_ lower, Index_ upper, Index_* right) : right(right), lower(lower), upper(upper) {}
215 Index_* right; // This is a pointer to the 'Node::right' of the parent of the node-to-be-added.
216 Index_ lower, upper; // Lower and upper ranges of the items in the node-to-be-added.
217 };
218 std::vector<BuildHistory> history;
219
220 while (1) {
221 my_nodes.emplace_back();
222 Node& node = my_nodes.back();
223
224 const Index_ gap = upper - lower;
225 assert(gap > 0);
226 if (gap == 1) { // i.e., we're at a leaf.
227 const auto& leaf = items[lower];
228 node.index = leaf.second;
229
230 // If we're at a leaf, we've finished this particular branch of the tree, so we can start rolling back through history.
231 if (history.empty()) {
232 return;
233 }
234 *(history.back().right) = my_nodes.size();
235 lower = history.back().lower;
236 upper = history.back().upper;
237 history.pop_back();
238 continue;
239 }
240
241 // Choose an arbitrary point and move it to the start of the [lower, upper) interval in 'items'; this is our new vantage point.
242 // Yes, I know that the modulo method does not provide strictly uniform values but statistical correctness doesn't really matter here,
243 // and I don't want std::uniform_int_distribution's implementation-specific behavior.
244 const Index_ vp = (rng() % gap + lower);
245 std::swap(items[lower], items[vp]);
246 const auto& vantage = items[lower];
247 node.index = vantage.second;
248 const Data_* vantage_ptr = coords + sanisizer::product_unsafe<std::size_t>(vantage.second, my_dim);
249
250 // Compute distances to the new vantage point.
251 // We +1 to exclude the vantage point itself, obviously.
252 const Index_ lower_p1 = lower + 1;
253 for (Index_ i = lower_p1 ; i < upper; ++i) {
254 const Data_* loc = coords + sanisizer::product_unsafe<std::size_t>(items[i].second, my_dim);
255 items[i].first = my_metric->raw(my_dim, vantage_ptr, loc);
256 }
257
258 if (gap > 2) {
259 // Partition around the median distance from the vantage point.
260 const Index_ median = lower_p1 + (gap - 1)/2;
261 std::nth_element(items.begin() + lower_p1, items.begin() + median, items.begin() + upper);
262
263 // Radius of the new node will be the distance to the median.
264 node.radius = my_metric->normalize(items[median].first);
265
266 // The next iteration will process the left node (i.e., inside the ball).
267 // We store the boundaries of the yet-to-be-added right node to the history for later processing.
268 history.emplace_back(median, upper, &(node.right));
269 node.left = my_nodes.size();
270 lower = lower_p1;
271 upper = median;
272
273 } else {
274 // Here we only have one child, as this node has two observations and one of them was already used as the vantage point.
275 // So the other observation is used directly as the right node.
276 const Index_ median = lower_p1;
277 node.radius = my_metric->normalize(items[median].first);
278 node.right = my_nodes.size();
279 lower = median;
280
281 // Several points worth mentioning here:
282 // - No need to set upper, as we'd end up just doing upper = upper and clang complains.
283 // - This code allows us to get a node where left = TERMINAL and right != TERMINAL, but the opposite is impossible.
284 // This fact is exploited in search_nn() for some minor optimizations.
285 }
286 }
287 }
288
289private:
290 std::vector<Index_> my_new_locations;
291
292public:
293 VptreePrebuilt(std::size_t num_dim, Index_ num_obs, std::vector<Data_> data, std::shared_ptr<const DistanceMetric_> metric, const VptreeOptions& options) :
294 my_dim(num_dim),
295 my_obs(num_obs),
296 my_data(std::move(data)),
297 my_metric(std::move(metric))
298 {
299 if (num_obs) {
300 build(options);
301
302 // Resorting data in place to match order of occurrence within 'nodes', for better cache locality.
303 auto used = sanisizer::create<std::vector<char> >(my_obs);
304 auto buffer = sanisizer::create<std::vector<Data_> >(my_dim);
305 sanisizer::resize(my_new_locations, my_obs);
306 auto host = my_data.data();
307
308 for (Index_ o = 0; o < num_obs; ++o) {
309 if (used[o]) {
310 continue;
311 }
312
313 auto& current = my_nodes[o];
314 my_new_locations[current.index] = o;
315 if (current.index == o) {
316 continue;
317 }
318
319 auto optr = host + sanisizer::product_unsafe<std::size_t>(o, my_dim);
320 std::copy_n(optr, my_dim, buffer.begin());
321 Index_ replacement = current.index;
322
323 do {
324 auto rptr = host + sanisizer::product_unsafe<std::size_t>(replacement, my_dim);
325 std::copy_n(rptr, my_dim, optr);
326 used[replacement] = 1;
327
328 const auto& next = my_nodes[replacement];
329 my_new_locations[next.index] = replacement;
330
331 optr = rptr;
332 replacement = next.index;
333 } while (replacement != o);
334
335 std::copy(buffer.begin(), buffer.end(), optr);
336 }
337 }
338 }
339
340private:
341 static bool can_progress_left(const Node& node, const Distance_ dist_to_vp, const Distance_ threshold) {
342 return node.left != TERMINAL && dist_to_vp - threshold <= node.radius;
343 }
344
345 static bool can_progress_right(const Node& node, const Distance_ dist_to_vp, const Distance_ threshold) {
346 // Using >= in the triangle inequality as there are some points that lie on the surface of the ball but are considered 'outside' the ball,
347 // e.g., the median point itself as well as anything with a tied distance.
348 return node.right != TERMINAL && dist_to_vp + threshold >= node.radius;
349 }
350
351 void search_nn(const Data_* target, NeighborQueue<Index_, Distance_>& nearest, std::vector<VptreeSearchHistory<Index_> >& history) const {
352 history.clear();
353 Index_ curnode_offset = 0;
354 Distance_ max_dist = std::numeric_limits<Distance_>::max();
355
356 while (1) {
357 auto nptr = my_data.data() + sanisizer::product_unsafe<std::size_t>(curnode_offset, my_dim);
358 const Distance_ dist_to_vp = my_metric->normalize(my_metric->raw(my_dim, nptr, target));
359
360 const auto& curnode = my_nodes[curnode_offset];
361 if (dist_to_vp <= max_dist) {
362 nearest.add(curnode.index, dist_to_vp);
363 if (nearest.is_full()) {
364 max_dist = nearest.limit(); // update value of max_dist (farthest point in result list)
365 }
366 }
367
368 if (dist_to_vp < curnode.radius) {
369 // If the target lies within the radius of ball, chances are that its neighbors also lie inside the ball.
370 // So we check the points inside the ball first (i.e., left node) to try to shrink max_dist as fast as possible.
371
372 // A quirk here is that, if dist_to_vp < curnode.radius, then can_progress_left must be true if curnode.left != TERMINAL.
373 // So we don't bother to compute the full function.
374 const bool can_left = curnode.left != TERMINAL;
375 const bool can_right = can_progress_right(curnode, dist_to_vp, max_dist);
376
377 if (can_left) {
378 if (can_right) {
379 history.emplace_back(false, curnode_offset);
380 }
381 curnode_offset = curnode.left;
382 continue;
383 } else if (can_right) {
384 curnode_offset = curnode.right;
385 continue;
386 }
387
388 } else {
389 // Otherwise, if the target lies at or outside the radius of the ball, chances are its neighbors also lie outside the ball.
390 // So we check the points outside the ball first (i.e., right node) to try to shrink max_dist as fast as possible.
391
392 // A quirk here is that, if dist_to_vp >= curnode.radius, then can_progress_right must be true if curnode.right != TERMINAL.
393 // So we don't bother to compute the full function.
394 const bool can_right = curnode.right != TERMINAL;
395 const bool can_left = can_progress_left(curnode, dist_to_vp, max_dist);
396
397 if (can_right) {
398 if (can_left) {
399 history.emplace_back(true, curnode_offset);
400 }
401 curnode_offset = curnode.right;
402 continue;
403 } else {
404 // The manner of construction of the VP tree prevents the existence of a node where right == TERMINAL but left != TERMINAL.
405 // As such, there's no need to consider the 'else if (can_left) {' condition that we would otherwise expect for symmetry with the inside-ball code.
406 assert(!can_left);
407 }
408 }
409
410 // We don't have anything else to do here, so we move back to the last branching node in our history.
411 if (history.empty()) {
412 return;
413 }
414
415 auto& histinfo = history.back();
416 if (!histinfo.right) {
417 curnode_offset = my_nodes[histinfo.node].right;
418 } else {
419 curnode_offset = my_nodes[histinfo.node].left;
420 }
421 history.pop_back();
422 }
423 }
424
425 template<bool count_only_, typename Output_>
426 void search_all(const Data_* target, const Distance_ threshold, Output_& all_neighbors, std::vector<VptreeSearchHistory<Index_> >& history) const {
427 history.clear();
428 Index_ curnode_offset = 0;
429
430 while (1) {
431 auto nptr = my_data.data() + sanisizer::product_unsafe<std::size_t>(curnode_offset, my_dim);
432 const Distance_ dist_to_vp = my_metric->normalize(my_metric->raw(my_dim, nptr, target));
433
434 const auto& curnode = my_nodes[curnode_offset];
435 if (dist_to_vp <= threshold) {
436 if constexpr(count_only_) {
437 ++all_neighbors;
438 } else {
439 all_neighbors.emplace_back(dist_to_vp, curnode.index);
440 }
441 }
442
443 const bool can_left = can_progress_left(curnode, dist_to_vp, threshold);
444 const bool can_right = can_progress_right(curnode, dist_to_vp, threshold);
445
446 // Unlike in search_nn(), we don't bother with different priorities for left/right.
447 // The threshold isn't going to change and we'd have to search both children anyway.
448 if (can_left) {
449 if (can_right) {
450 history.emplace_back(false, curnode_offset); // false is just a dummy value and is ignored in this rest of this function.
451 }
452 curnode_offset = curnode.left;
453 continue;
454 } else if (can_right) {
455 curnode_offset = curnode.right;
456 continue;
457 }
458
459 // We don't have anything else to do here, so we move back to the last branching node in our history.
460 if (history.empty()) {
461 return;
462 }
463
464 auto& histinfo = history.back();
465 curnode_offset = my_nodes[histinfo.node].right;
466 history.pop_back();
467 }
468 }
469
470 friend class VptreeSearcher<Index_, Data_, Distance_, DistanceMetric_>;
471
472public:
473 std::unique_ptr<Searcher<Index_, Data_, Distance_> > initialize() const {
474 return initialize_known();
475 }
476
477 auto initialize_known() const {
478 return std::make_unique<VptreeSearcher<Index_, Data_, Distance_, DistanceMetric_> >(*this);
479 }
480
481public:
482 void save(const std::filesystem::path& dir) const {
483 quick_save(dir / "ALGORITHM", vptree_prebuilt_save_name, std::strlen(vptree_prebuilt_save_name));
484 quick_save(dir / "DATA", my_data.data(), my_data.size());
485 quick_save(dir / "NUM_OBS", &my_obs, 1);
486 quick_save(dir / "NUM_DIM", &my_dim, 1);
487 quick_save(dir / "NODES", my_nodes.data(), my_nodes.size());
488 quick_save(dir / "NEW_LOCATIONS", my_new_locations.data(), my_new_locations.size());
489
490 const auto distdir = dir / "DISTANCE";
491 std::filesystem::create_directory(distdir);
492 my_metric->save(distdir);
493 }
494
495 VptreePrebuilt(const std::filesystem::path& dir) {
496 quick_load(dir / "NUM_OBS", &my_obs, 1);
497 quick_load(dir / "NUM_DIM", &my_dim, 1);
498
499 my_data.resize(sanisizer::product<I<decltype(my_data.size())> >(my_obs, my_dim));
500 quick_load(dir / "DATA", my_data.data(), my_data.size());
501
502 sanisizer::resize(my_nodes, my_obs);
503 quick_load(dir / "NODES", my_nodes.data(), my_nodes.size());
504
505 sanisizer::resize(my_new_locations, my_obs);
506 quick_load(dir / "NEW_LOCATIONS", my_new_locations.data(), my_new_locations.size());
507
508 auto dptr = load_distance_metric_raw<Data_, Distance_>(dir / "DISTANCE");
509 auto xptr = dynamic_cast<DistanceMetric_*>(dptr);
510 if (xptr == NULL) {
511 throw std::runtime_error("cannot cast the loaded distance metric to a DistanceMetric_");
512 }
513 my_metric.reset(xptr);
514 }
515};
561template<
562 typename Index_,
563 typename Data_,
564 typename Distance_,
565 class Matrix_ = Matrix<Index_, Data_>,
566 class DistanceMetric_ = DistanceMetric<Data_, Distance_>
567>
568class VptreeBuilder final : public Builder<Index_, Data_, Distance_, Matrix_> {
569public:
574 VptreeBuilder(std::shared_ptr<const DistanceMetric_> metric, VptreeOptions options) : my_metric(std::move(metric)), my_options(std::move(options)) {}
575
581 VptreeBuilder(std::shared_ptr<const DistanceMetric_> metric) : VptreeBuilder(std::move(metric), {}) {}
582
588 return my_options;
589 }
590
591private:
592 std::shared_ptr<const DistanceMetric_> my_metric;
593 VptreeOptions my_options;
594
595public:
599 Prebuilt<Index_, Data_, Distance_>* build_raw(const Matrix_& data) const {
600 return build_known_raw(data);
601 }
606public:
610 auto build_known_raw(const Matrix_& data) const {
611 std::size_t ndim = data.num_dimensions();
612 Index_ nobs = data.num_observations();
613 auto work = data.new_known_extractor();
614
615 // We assume that that vector::size_type <= size_t, otherwise data() wouldn't be a contiguous array.
616 std::vector<Data_> store(sanisizer::product<typename std::vector<Data_>::size_type>(ndim, nobs));
617 for (Index_ o = 0; o < nobs; ++o) {
618 std::copy_n(work->next(), ndim, store.data() + sanisizer::product_unsafe<std::size_t>(o, ndim));
619 }
620
621 return new VptreePrebuilt<Index_, Data_, Distance_, DistanceMetric_>(ndim, nobs, std::move(store), my_metric, my_options);
622 }
623
627 auto build_known_unique(const Matrix_& data) const {
628 return std::unique_ptr<I<decltype(*build_known_raw(data))> >(build_known_raw(data));
629 }
630
634 auto build_known_shared(const Matrix_& data) const {
635 return std::shared_ptr<I<decltype(*build_known_raw(data))> >(build_known_raw(data));
636 }
637};
638
639}
640
641#endif
Interface to build nearest-neighbor indices.
Interface for the input matrix.
Helper class to track nearest neighbors.
Interface for prebuilt nearest-neighbor indices.
Interface to build nearest-neighbor search indices.
Definition Builder.hpp:28
virtual Prebuilt< Index_, Data_, Distance_ > * build_raw(const Matrix_ &data) const =0
Interface for prebuilt nearest-neighbor search indices.
Definition Prebuilt.hpp:29
Perform a nearest neighbor search based on a vantage point (VP) tree.
Definition Vptree.hpp:568
VptreeBuilder(std::shared_ptr< const DistanceMetric_ > metric)
Definition Vptree.hpp:581
auto build_known_unique(const Matrix_ &data) const
Definition Vptree.hpp:627
VptreeOptions & get_options()
Definition Vptree.hpp:587
VptreeBuilder(std::shared_ptr< const DistanceMetric_ > metric, VptreeOptions options)
Definition Vptree.hpp:574
auto build_known_raw(const Matrix_ &data) const
Definition Vptree.hpp:610
auto build_known_shared(const Matrix_ &data) const
Definition Vptree.hpp:634
Classes for distance calculations.
Collection of KNN algorithms.
Definition Bruteforce.hpp:31
void quick_load(const std::filesystem::path &path, Input_ *const contents, const Length_ length)
Definition utils.hpp:57
Index_ count_all_neighbors_without_self(Index_ count)
Definition report_all_neighbors.hpp:23
void quick_save(const std::filesystem::path &path, const Input_ *const contents, const Length_ length)
Definition utils.hpp:33
void report_all_neighbors(std::vector< std::pair< Distance_, Index_ > > &all_neighbors, std::vector< Index_ > *output_indices, std::vector< Distance_ > *output_distances, Index_ self)
Definition report_all_neighbors.hpp:106
Format the output for Searcher::search_all().
Options for VptreeBuilder construction.
Definition Vptree.hpp:42
std::optional< typename std::mt19937_64::result_type > seed
Definition Vptree.hpp:47
Miscellaneous utilities for knncolle