nanoflann
C++ header-only ANN library
Loading...
Searching...
No Matches
nanoflann.hpp
1/***********************************************************************
2 * Software License Agreement (BSD License)
3 *
4 * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
5 * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
6 * Copyright 2011-2024 Jose Luis Blanco (joseluisblancoc@gmail.com).
7 * All rights reserved.
8 *
9 * THE BSD LICENSE
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 *
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 *************************************************************************/
32
45#pragma once
46
47#include <algorithm>
48#include <array>
49#include <atomic>
50#include <cassert>
51#include <cmath> // for abs()
52#include <cstdint>
53#include <cstdlib> // for abs()
54#include <functional> // std::reference_wrapper
55#include <future>
56#include <istream>
57#include <limits> // std::numeric_limits
58#include <ostream>
59#include <stdexcept>
60#include <unordered_set>
61#include <vector>
62
64#define NANOFLANN_VERSION 0x161
65
66// Avoid conflicting declaration of min/max macros in Windows headers
67#if !defined(NOMINMAX) && \
68 (defined(_WIN32) || defined(_WIN32_) || defined(WIN32) || defined(_WIN64))
69#define NOMINMAX
70#ifdef max
71#undef max
72#undef min
73#endif
74#endif
75// Avoid conflicts with X11 headers
76#ifdef None
77#undef None
78#endif
79
80namespace nanoflann
81{
86template <typename T>
88{
89 return static_cast<T>(3.14159265358979323846);
90}
91
96template <typename T, typename = int>
97struct has_resize : std::false_type
98{
99};
100
101template <typename T>
102struct has_resize<T, decltype((void)std::declval<T>().resize(1), 0)>
103 : std::true_type
104{
105};
106
107template <typename T, typename = int>
108struct has_assign : std::false_type
109{
110};
111
112template <typename T>
113struct has_assign<T, decltype((void)std::declval<T>().assign(1, 0), 0)>
114 : std::true_type
115{
116};
117
121template <typename Container>
122inline typename std::enable_if<has_resize<Container>::value, void>::type resize(
123 Container& c, const size_t nElements)
124{
125 c.resize(nElements);
126}
127
132template <typename Container>
133inline typename std::enable_if<!has_resize<Container>::value, void>::type
134 resize(Container& c, const size_t nElements)
135{
136 if (nElements != c.size())
137 throw std::logic_error("Try to change the size of a std::array.");
138}
139
143template <typename Container, typename T>
144inline typename std::enable_if<has_assign<Container>::value, void>::type assign(
145 Container& c, const size_t nElements, const T& value)
146{
147 c.assign(nElements, value);
148}
149
153template <typename Container, typename T>
154inline typename std::enable_if<!has_assign<Container>::value, void>::type
155 assign(Container& c, const size_t nElements, const T& value)
156{
157 for (size_t i = 0; i < nElements; i++) c[i] = value;
158}
159
162{
164 template <typename PairType>
165 bool operator()(const PairType& p1, const PairType& p2) const
166 {
167 return p1.second < p2.second;
168 }
169};
170
179template <typename IndexType = size_t, typename DistanceType = double>
181{
182 ResultItem() = default;
183 ResultItem(const IndexType index, const DistanceType distance)
184 : first(index), second(distance)
185 {
186 }
187
188 IndexType first;
189 DistanceType second;
190};
191
196template <
197 typename _DistanceType, typename _IndexType = size_t,
198 typename _CountType = size_t>
200{
201 public:
202 using DistanceType = _DistanceType;
203 using IndexType = _IndexType;
204 using CountType = _CountType;
205
206 private:
207 IndexType* indices;
208 DistanceType* dists;
209 CountType capacity;
210 CountType count;
211
212 public:
213 explicit KNNResultSet(CountType capacity_)
214 : indices(nullptr), dists(nullptr), capacity(capacity_), count(0)
215 {
216 }
217
218 void init(IndexType* indices_, DistanceType* dists_)
219 {
220 indices = indices_;
221 dists = dists_;
222 count = 0;
223 if (capacity)
224 dists[capacity - 1] = (std::numeric_limits<DistanceType>::max)();
225 }
226
227 CountType size() const { return count; }
228 bool empty() const { return count == 0; }
229 bool full() const { return count == capacity; }
230
236 bool addPoint(DistanceType dist, IndexType index)
237 {
238 CountType i;
239 for (i = count; i > 0; --i)
240 {
243#ifdef NANOFLANN_FIRST_MATCH
244 if ((dists[i - 1] > dist) ||
245 ((dist == dists[i - 1]) && (indices[i - 1] > index)))
246 {
247#else
248 if (dists[i - 1] > dist)
249 {
250#endif
251 if (i < capacity)
252 {
253 dists[i] = dists[i - 1];
254 indices[i] = indices[i - 1];
255 }
256 }
257 else
258 break;
259 }
260 if (i < capacity)
261 {
262 dists[i] = dist;
263 indices[i] = index;
264 }
265 if (count < capacity) count++;
266
267 // tell caller that the search shall continue
268 return true;
269 }
270
271 DistanceType worstDist() const { return dists[capacity - 1]; }
272
273 void sort()
274 {
275 // already sorted
276 }
277};
278
280template <
281 typename _DistanceType, typename _IndexType = size_t,
282 typename _CountType = size_t>
284{
285 public:
286 using DistanceType = _DistanceType;
287 using IndexType = _IndexType;
288 using CountType = _CountType;
289
290 private:
291 IndexType* indices;
292 DistanceType* dists;
293 CountType capacity;
294 CountType count;
295 DistanceType maximumSearchDistanceSquared;
296
297 public:
298 explicit RKNNResultSet(
299 CountType capacity_, DistanceType maximumSearchDistanceSquared_)
300 : indices(nullptr),
301 dists(nullptr),
302 capacity(capacity_),
303 count(0),
304 maximumSearchDistanceSquared(maximumSearchDistanceSquared_)
305 {
306 }
307
308 void init(IndexType* indices_, DistanceType* dists_)
309 {
310 indices = indices_;
311 dists = dists_;
312 count = 0;
313 if (capacity) dists[capacity - 1] = maximumSearchDistanceSquared;
314 }
315
316 CountType size() const { return count; }
317 bool empty() const { return count == 0; }
318 bool full() const { return count == capacity; }
319
325 bool addPoint(DistanceType dist, IndexType index)
326 {
327 CountType i;
328 for (i = count; i > 0; --i)
329 {
332#ifdef NANOFLANN_FIRST_MATCH
333 if ((dists[i - 1] > dist) ||
334 ((dist == dists[i - 1]) && (indices[i - 1] > index)))
335 {
336#else
337 if (dists[i - 1] > dist)
338 {
339#endif
340 if (i < capacity)
341 {
342 dists[i] = dists[i - 1];
343 indices[i] = indices[i - 1];
344 }
345 }
346 else
347 break;
348 }
349 if (i < capacity)
350 {
351 dists[i] = dist;
352 indices[i] = index;
353 }
354 if (count < capacity) count++;
355
356 // tell caller that the search shall continue
357 return true;
358 }
359
360 DistanceType worstDist() const { return dists[capacity - 1]; }
361
362 void sort()
363 {
364 // already sorted
365 }
366};
367
371template <typename _DistanceType, typename _IndexType = size_t>
373{
374 public:
375 using DistanceType = _DistanceType;
376 using IndexType = _IndexType;
377
378 public:
379 const DistanceType radius;
380
381 std::vector<ResultItem<IndexType, DistanceType>>& m_indices_dists;
382
383 explicit RadiusResultSet(
384 DistanceType radius_,
385 std::vector<ResultItem<IndexType, DistanceType>>& indices_dists)
386 : radius(radius_), m_indices_dists(indices_dists)
387 {
388 init();
389 }
390
391 void init() { clear(); }
392 void clear() { m_indices_dists.clear(); }
393
394 size_t size() const { return m_indices_dists.size(); }
395 size_t empty() const { return m_indices_dists.empty(); }
396
397 bool full() const { return true; }
398
404 bool addPoint(DistanceType dist, IndexType index)
405 {
406 if (dist < radius) m_indices_dists.emplace_back(index, dist);
407 return true;
408 }
409
410 DistanceType worstDist() const { return radius; }
411
417 {
418 if (m_indices_dists.empty())
419 throw std::runtime_error(
420 "Cannot invoke RadiusResultSet::worst_item() on "
421 "an empty list of results.");
422 auto it = std::max_element(
423 m_indices_dists.begin(), m_indices_dists.end(), IndexDist_Sorter());
424 return *it;
425 }
426
427 void sort()
428 {
429 std::sort(
430 m_indices_dists.begin(), m_indices_dists.end(), IndexDist_Sorter());
431 }
432};
433
438template <typename T>
439void save_value(std::ostream& stream, const T& value)
440{
441 stream.write(reinterpret_cast<const char*>(&value), sizeof(T));
442}
443
444template <typename T>
445void save_value(std::ostream& stream, const std::vector<T>& value)
446{
447 size_t size = value.size();
448 stream.write(reinterpret_cast<const char*>(&size), sizeof(size_t));
449 stream.write(reinterpret_cast<const char*>(value.data()), sizeof(T) * size);
450}
451
452template <typename T>
453void load_value(std::istream& stream, T& value)
454{
455 stream.read(reinterpret_cast<char*>(&value), sizeof(T));
456}
457
458template <typename T>
459void load_value(std::istream& stream, std::vector<T>& value)
460{
461 size_t size;
462 stream.read(reinterpret_cast<char*>(&size), sizeof(size_t));
463 value.resize(size);
464 stream.read(reinterpret_cast<char*>(value.data()), sizeof(T) * size);
465}
471struct Metric
472{
473};
474
485template <
486 class T, class DataSource, typename _DistanceType = T,
487 typename IndexType = uint32_t>
489{
490 using ElementType = T;
491 using DistanceType = _DistanceType;
492
493 const DataSource& data_source;
494
495 L1_Adaptor(const DataSource& _data_source) : data_source(_data_source) {}
496
497 DistanceType evalMetric(
498 const T* a, const IndexType b_idx, size_t size,
499 DistanceType worst_dist = -1) const
500 {
501 DistanceType result = DistanceType();
502 const T* last = a + size;
503 const T* lastgroup = last - 3;
504 size_t d = 0;
505
506 /* Process 4 items with each loop for efficiency. */
507 while (a < lastgroup)
508 {
509 const DistanceType diff0 =
510 std::abs(a[0] - data_source.kdtree_get_pt(b_idx, d++));
511 const DistanceType diff1 =
512 std::abs(a[1] - data_source.kdtree_get_pt(b_idx, d++));
513 const DistanceType diff2 =
514 std::abs(a[2] - data_source.kdtree_get_pt(b_idx, d++));
515 const DistanceType diff3 =
516 std::abs(a[3] - data_source.kdtree_get_pt(b_idx, d++));
517 result += diff0 + diff1 + diff2 + diff3;
518 a += 4;
519 if ((worst_dist > 0) && (result > worst_dist)) { return result; }
520 }
521 /* Process last 0-3 components. Not needed for standard vector lengths.
522 */
523 while (a < last)
524 {
525 result += std::abs(*a++ - data_source.kdtree_get_pt(b_idx, d++));
526 }
527 return result;
528 }
529
530 template <typename U, typename V>
531 DistanceType accum_dist(const U a, const V b, const size_t) const
532 {
533 return std::abs(a - b);
534 }
535};
536
547template <
548 class T, class DataSource, typename _DistanceType = T,
549 typename IndexType = uint32_t>
551{
552 using ElementType = T;
553 using DistanceType = _DistanceType;
554
555 const DataSource& data_source;
556
557 L2_Adaptor(const DataSource& _data_source) : data_source(_data_source) {}
558
559 DistanceType evalMetric(
560 const T* a, const IndexType b_idx, size_t size,
561 DistanceType worst_dist = -1) const
562 {
563 DistanceType result = DistanceType();
564 const T* last = a + size;
565 const T* lastgroup = last - 3;
566 size_t d = 0;
567
568 /* Process 4 items with each loop for efficiency. */
569 while (a < lastgroup)
570 {
571 const DistanceType diff0 =
572 a[0] - data_source.kdtree_get_pt(b_idx, d++);
573 const DistanceType diff1 =
574 a[1] - data_source.kdtree_get_pt(b_idx, d++);
575 const DistanceType diff2 =
576 a[2] - data_source.kdtree_get_pt(b_idx, d++);
577 const DistanceType diff3 =
578 a[3] - data_source.kdtree_get_pt(b_idx, d++);
579 result +=
580 diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;
581 a += 4;
582 if ((worst_dist > 0) && (result > worst_dist)) { return result; }
583 }
584 /* Process last 0-3 components. Not needed for standard vector lengths.
585 */
586 while (a < last)
587 {
588 const DistanceType diff0 =
589 *a++ - data_source.kdtree_get_pt(b_idx, d++);
590 result += diff0 * diff0;
591 }
592 return result;
593 }
594
595 template <typename U, typename V>
596 DistanceType accum_dist(const U a, const V b, const size_t) const
597 {
598 return (a - b) * (a - b);
599 }
600};
601
612template <
613 class T, class DataSource, typename _DistanceType = T,
614 typename IndexType = uint32_t>
616{
617 using ElementType = T;
618 using DistanceType = _DistanceType;
619
620 const DataSource& data_source;
621
622 L2_Simple_Adaptor(const DataSource& _data_source)
623 : data_source(_data_source)
624 {
625 }
626
627 DistanceType evalMetric(
628 const T* a, const IndexType b_idx, size_t size) const
629 {
630 DistanceType result = DistanceType();
631 for (size_t i = 0; i < size; ++i)
632 {
633 const DistanceType diff =
634 a[i] - data_source.kdtree_get_pt(b_idx, i);
635 result += diff * diff;
636 }
637 return result;
638 }
639
640 template <typename U, typename V>
641 DistanceType accum_dist(const U a, const V b, const size_t) const
642 {
643 return (a - b) * (a - b);
644 }
645};
646
657template <
658 class T, class DataSource, typename _DistanceType = T,
659 typename IndexType = uint32_t>
661{
662 using ElementType = T;
663 using DistanceType = _DistanceType;
664
665 const DataSource& data_source;
666
667 SO2_Adaptor(const DataSource& _data_source) : data_source(_data_source) {}
668
669 DistanceType evalMetric(
670 const T* a, const IndexType b_idx, size_t size) const
671 {
672 return accum_dist(
673 a[size - 1], data_source.kdtree_get_pt(b_idx, size - 1), size - 1);
674 }
675
678 template <typename U, typename V>
679 DistanceType accum_dist(const U a, const V b, const size_t) const
680 {
681 DistanceType result = DistanceType();
682 DistanceType PI = pi_const<DistanceType>();
683 result = b - a;
684 if (result > PI)
685 result -= 2 * PI;
686 else if (result < -PI)
687 result += 2 * PI;
688 return result;
689 }
690};
691
702template <
703 class T, class DataSource, typename _DistanceType = T,
704 typename IndexType = uint32_t>
706{
707 using ElementType = T;
708 using DistanceType = _DistanceType;
709
711 distance_L2_Simple;
712
713 SO3_Adaptor(const DataSource& _data_source)
714 : distance_L2_Simple(_data_source)
715 {
716 }
717
718 DistanceType evalMetric(
719 const T* a, const IndexType b_idx, size_t size) const
720 {
721 return distance_L2_Simple.evalMetric(a, b_idx, size);
722 }
723
724 template <typename U, typename V>
725 DistanceType accum_dist(const U a, const V b, const size_t idx) const
726 {
727 return distance_L2_Simple.accum_dist(a, b, idx);
728 }
729};
730
732struct metric_L1 : public Metric
733{
734 template <class T, class DataSource, typename IndexType = uint32_t>
739};
742struct metric_L2 : public Metric
743{
744 template <class T, class DataSource, typename IndexType = uint32_t>
749};
753{
754 template <class T, class DataSource, typename IndexType = uint32_t>
759};
761struct metric_SO2 : public Metric
762{
763 template <class T, class DataSource, typename IndexType = uint32_t>
768};
770struct metric_SO3 : public Metric
771{
772 template <class T, class DataSource, typename IndexType = uint32_t>
777};
778
784enum class KDTreeSingleIndexAdaptorFlags
785{
786 None = 0,
787 SkipInitialBuildIndex = 1
788};
789
790inline std::underlying_type<KDTreeSingleIndexAdaptorFlags>::type operator&(
791 KDTreeSingleIndexAdaptorFlags lhs, KDTreeSingleIndexAdaptorFlags rhs)
792{
793 using underlying =
794 typename std::underlying_type<KDTreeSingleIndexAdaptorFlags>::type;
795 return static_cast<underlying>(lhs) & static_cast<underlying>(rhs);
796}
797
800{
802 size_t _leaf_max_size = 10,
803 KDTreeSingleIndexAdaptorFlags _flags =
804 KDTreeSingleIndexAdaptorFlags::None,
805 unsigned int _n_thread_build = 1)
806 : leaf_max_size(_leaf_max_size),
807 flags(_flags),
808 n_thread_build(_n_thread_build)
809 {
810 }
811
812 size_t leaf_max_size;
813 KDTreeSingleIndexAdaptorFlags flags;
814 unsigned int n_thread_build;
815};
816
819{
820 SearchParameters(float eps_ = 0, bool sorted_ = true)
821 : eps(eps_), sorted(sorted_)
822 {
823 }
824
825 float eps;
826 bool sorted;
828};
849{
850 static constexpr size_t WORDSIZE = 16; // WORDSIZE must >= 8
851 static constexpr size_t BLOCKSIZE = 8192;
852
853 /* We maintain memory alignment to word boundaries by requiring that all
854 allocations be in multiples of the machine wordsize. */
855 /* Size of machine word in bytes. Must be power of 2. */
856 /* Minimum number of bytes requested at a time from the system. Must be
857 * multiple of WORDSIZE. */
858
859 using Size = size_t;
860
861 Size remaining_ = 0;
862 void* base_ = nullptr;
863 void* loc_ = nullptr;
864
865 void internal_init()
866 {
867 remaining_ = 0;
868 base_ = nullptr;
869 usedMemory = 0;
870 wastedMemory = 0;
871 }
872
873 public:
874 Size usedMemory = 0;
875 Size wastedMemory = 0;
876
880 PooledAllocator() { internal_init(); }
881
885 ~PooledAllocator() { free_all(); }
886
888 void free_all()
889 {
890 while (base_ != nullptr)
891 {
892 // Get pointer to prev block
893 void* prev = *(static_cast<void**>(base_));
894 ::free(base_);
895 base_ = prev;
896 }
897 internal_init();
898 }
899
904 void* malloc(const size_t req_size)
905 {
906 /* Round size up to a multiple of wordsize. The following expression
907 only works for WORDSIZE that is a power of 2, by masking last bits
908 of incremented size to zero.
909 */
910 const Size size = (req_size + (WORDSIZE - 1)) & ~(WORDSIZE - 1);
911
912 /* Check whether a new block must be allocated. Note that the first
913 word of a block is reserved for a pointer to the previous block.
914 */
915 if (size > remaining_)
916 {
917 wastedMemory += remaining_;
918
919 /* Allocate new storage. */
920 const Size blocksize =
921 size > BLOCKSIZE ? size + WORDSIZE : BLOCKSIZE + WORDSIZE;
922
923 // use the standard C malloc to allocate memory
924 void* m = ::malloc(blocksize);
925 if (!m)
926 {
927 fprintf(stderr, "Failed to allocate memory.\n");
928 throw std::bad_alloc();
929 }
930
931 /* Fill first word of new block with pointer to previous block. */
932 static_cast<void**>(m)[0] = base_;
933 base_ = m;
934
935 remaining_ = blocksize - WORDSIZE;
936 loc_ = static_cast<char*>(m) + WORDSIZE;
937 }
938 void* rloc = loc_;
939 loc_ = static_cast<char*>(loc_) + size;
940 remaining_ -= size;
941
942 usedMemory += size;
943
944 return rloc;
945 }
946
954 template <typename T>
955 T* allocate(const size_t count = 1)
956 {
957 T* mem = static_cast<T*>(this->malloc(sizeof(T) * count));
958 return mem;
959 }
960};
969template <int32_t DIM, typename T>
971{
972 using type = std::array<T, DIM>;
973};
975template <typename T>
976struct array_or_vector<-1, T>
977{
978 using type = std::vector<T>;
979};
980
997template <
998 class Derived, typename Distance, class DatasetAdaptor, int32_t DIM = -1,
999 typename index_t = uint32_t>
1001{
1002 public:
1005 void freeIndex(Derived& obj)
1006 {
1007 obj.pool_.free_all();
1008 obj.root_node_ = nullptr;
1009 obj.size_at_index_build_ = 0;
1010 }
1011
1012 using ElementType = typename Distance::ElementType;
1013 using DistanceType = typename Distance::DistanceType;
1014 using IndexType = index_t;
1015
1019 std::vector<IndexType> vAcc_;
1020
1021 using Offset = typename decltype(vAcc_)::size_type;
1022 using Size = typename decltype(vAcc_)::size_type;
1023 using Dimension = int32_t;
1024
1025 /*---------------------------
1026 * Internal Data Structures
1027 * --------------------------*/
1028 struct Node
1029 {
1032 union
1033 {
1034 struct leaf
1035 {
1036 Offset left, right;
1037 } lr;
1038 struct nonleaf
1039 {
1040 Dimension divfeat;
1042 DistanceType divlow, divhigh;
1043 } sub;
1044 } node_type;
1045
1047 Node *child1 = nullptr, *child2 = nullptr;
1048 };
1049
1050 using NodePtr = Node*;
1051 using NodeConstPtr = const Node*;
1052
1054 {
1055 ElementType low, high;
1056 };
1057
1058 NodePtr root_node_ = nullptr;
1059
1060 Size leaf_max_size_ = 0;
1061
1063 Size n_thread_build_ = 1;
1065 Size size_ = 0;
1067 Size size_at_index_build_ = 0;
1068 Dimension dim_ = 0;
1069
1072 using BoundingBox = typename array_or_vector<DIM, Interval>::type;
1073
1076 using distance_vector_t = typename array_or_vector<DIM, DistanceType>::type;
1077
1080
1089
1091 Size size(const Derived& obj) const { return obj.size_; }
1092
1094 Size veclen(const Derived& obj) { return DIM > 0 ? DIM : obj.dim; }
1095
1097 ElementType dataset_get(
1098 const Derived& obj, IndexType element, Dimension component) const
1099 {
1100 return obj.dataset_.kdtree_get_pt(element, component);
1101 }
1102
1107 Size usedMemory(Derived& obj)
1108 {
1109 return obj.pool_.usedMemory + obj.pool_.wastedMemory +
1110 obj.dataset_.kdtree_get_point_count() *
1111 sizeof(IndexType); // pool memory and vind array memory
1112 }
1113
1114 void computeMinMax(
1115 const Derived& obj, Offset ind, Size count, Dimension element,
1116 ElementType& min_elem, ElementType& max_elem)
1117 {
1118 min_elem = dataset_get(obj, vAcc_[ind], element);
1119 max_elem = min_elem;
1120 for (Offset i = 1; i < count; ++i)
1121 {
1122 ElementType val = dataset_get(obj, vAcc_[ind + i], element);
1123 if (val < min_elem) min_elem = val;
1124 if (val > max_elem) max_elem = val;
1125 }
1126 }
1127
1136 Derived& obj, const Offset left, const Offset right, BoundingBox& bbox)
1137 {
1138 NodePtr node = obj.pool_.template allocate<Node>(); // allocate memory
1139 const auto dims = (DIM > 0 ? DIM : obj.dim_);
1140
1141 /* If too few exemplars remain, then make this a leaf node. */
1142 if ((right - left) <= static_cast<Offset>(obj.leaf_max_size_))
1143 {
1144 node->child1 = node->child2 = nullptr; /* Mark as leaf node. */
1145 node->node_type.lr.left = left;
1146 node->node_type.lr.right = right;
1147
1148 // compute bounding-box of leaf points
1149 for (Dimension i = 0; i < dims; ++i)
1150 {
1151 bbox[i].low = dataset_get(obj, obj.vAcc_[left], i);
1152 bbox[i].high = dataset_get(obj, obj.vAcc_[left], i);
1153 }
1154 for (Offset k = left + 1; k < right; ++k)
1155 {
1156 for (Dimension i = 0; i < dims; ++i)
1157 {
1158 const auto val = dataset_get(obj, obj.vAcc_[k], i);
1159 if (bbox[i].low > val) bbox[i].low = val;
1160 if (bbox[i].high < val) bbox[i].high = val;
1161 }
1162 }
1163 }
1164 else
1165 {
1166 Offset idx;
1167 Dimension cutfeat;
1168 DistanceType cutval;
1169 middleSplit_(obj, left, right - left, idx, cutfeat, cutval, bbox);
1170
1171 node->node_type.sub.divfeat = cutfeat;
1172
1173 BoundingBox left_bbox(bbox);
1174 left_bbox[cutfeat].high = cutval;
1175 node->child1 = this->divideTree(obj, left, left + idx, left_bbox);
1176
1177 BoundingBox right_bbox(bbox);
1178 right_bbox[cutfeat].low = cutval;
1179 node->child2 = this->divideTree(obj, left + idx, right, right_bbox);
1180
1181 node->node_type.sub.divlow = left_bbox[cutfeat].high;
1182 node->node_type.sub.divhigh = right_bbox[cutfeat].low;
1183
1184 for (Dimension i = 0; i < dims; ++i)
1185 {
1186 bbox[i].low = std::min(left_bbox[i].low, right_bbox[i].low);
1187 bbox[i].high = std::max(left_bbox[i].high, right_bbox[i].high);
1188 }
1189 }
1190
1191 return node;
1192 }
1193
1205 Derived& obj, const Offset left, const Offset right, BoundingBox& bbox,
1206 std::atomic<unsigned int>& thread_count, std::mutex& mutex)
1207 {
1208 std::unique_lock<std::mutex> lock(mutex);
1209 NodePtr node = obj.pool_.template allocate<Node>(); // allocate memory
1210 lock.unlock();
1211
1212 const auto dims = (DIM > 0 ? DIM : obj.dim_);
1213
1214 /* If too few exemplars remain, then make this a leaf node. */
1215 if ((right - left) <= static_cast<Offset>(obj.leaf_max_size_))
1216 {
1217 node->child1 = node->child2 = nullptr; /* Mark as leaf node. */
1218 node->node_type.lr.left = left;
1219 node->node_type.lr.right = right;
1220
1221 // compute bounding-box of leaf points
1222 for (Dimension i = 0; i < dims; ++i)
1223 {
1224 bbox[i].low = dataset_get(obj, obj.vAcc_[left], i);
1225 bbox[i].high = dataset_get(obj, obj.vAcc_[left], i);
1226 }
1227 for (Offset k = left + 1; k < right; ++k)
1228 {
1229 for (Dimension i = 0; i < dims; ++i)
1230 {
1231 const auto val = dataset_get(obj, obj.vAcc_[k], i);
1232 if (bbox[i].low > val) bbox[i].low = val;
1233 if (bbox[i].high < val) bbox[i].high = val;
1234 }
1235 }
1236 }
1237 else
1238 {
1239 Offset idx;
1240 Dimension cutfeat;
1241 DistanceType cutval;
1242 middleSplit_(obj, left, right - left, idx, cutfeat, cutval, bbox);
1243
1244 node->node_type.sub.divfeat = cutfeat;
1245
1246 std::future<NodePtr> right_future;
1247
1248 BoundingBox right_bbox(bbox);
1249 right_bbox[cutfeat].low = cutval;
1250 if (++thread_count < n_thread_build_)
1251 {
1252 // Concurrent right sub-tree
1253 right_future = std::async(
1254 std::launch::async, &KDTreeBaseClass::divideTreeConcurrent,
1255 this, std::ref(obj), left + idx, right,
1256 std::ref(right_bbox), std::ref(thread_count),
1257 std::ref(mutex));
1258 }
1259 else { --thread_count; }
1260
1261 BoundingBox left_bbox(bbox);
1262 left_bbox[cutfeat].high = cutval;
1263 node->child1 = this->divideTreeConcurrent(
1264 obj, left, left + idx, left_bbox, thread_count, mutex);
1265
1266 if (right_future.valid())
1267 {
1268 // Block and wait for concurrent right sub-tree
1269 node->child2 = right_future.get();
1270 --thread_count;
1271 }
1272 else
1273 {
1274 node->child2 = this->divideTreeConcurrent(
1275 obj, left + idx, right, right_bbox, thread_count, mutex);
1276 }
1277
1278 node->node_type.sub.divlow = left_bbox[cutfeat].high;
1279 node->node_type.sub.divhigh = right_bbox[cutfeat].low;
1280
1281 for (Dimension i = 0; i < dims; ++i)
1282 {
1283 bbox[i].low = std::min(left_bbox[i].low, right_bbox[i].low);
1284 bbox[i].high = std::max(left_bbox[i].high, right_bbox[i].high);
1285 }
1286 }
1287
1288 return node;
1289 }
1290
1291 void middleSplit_(
1292 const Derived& obj, const Offset ind, const Size count, Offset& index,
1293 Dimension& cutfeat, DistanceType& cutval, const BoundingBox& bbox)
1294 {
1295 const auto dims = (DIM > 0 ? DIM : obj.dim_);
1296 const auto EPS = static_cast<DistanceType>(0.00001);
1297 ElementType max_span = bbox[0].high - bbox[0].low;
1298 for (Dimension i = 1; i < dims; ++i)
1299 {
1300 ElementType span = bbox[i].high - bbox[i].low;
1301 if (span > max_span) { max_span = span; }
1302 }
1303 ElementType max_spread = -1;
1304 cutfeat = 0;
1305 ElementType min_elem = 0, max_elem = 0;
1306 for (Dimension i = 0; i < dims; ++i)
1307 {
1308 ElementType span = bbox[i].high - bbox[i].low;
1309 if (span > (1 - EPS) * max_span)
1310 {
1311 ElementType min_elem_, max_elem_;
1312 computeMinMax(obj, ind, count, i, min_elem_, max_elem_);
1313 ElementType spread = max_elem_ - min_elem_;
1314 if (spread > max_spread)
1315 {
1316 cutfeat = i;
1317 max_spread = spread;
1318 min_elem = min_elem_;
1319 max_elem = max_elem_;
1320 }
1321 }
1322 }
1323 // split in the middle
1324 DistanceType split_val = (bbox[cutfeat].low + bbox[cutfeat].high) / 2;
1325
1326 if (split_val < min_elem)
1327 cutval = min_elem;
1328 else if (split_val > max_elem)
1329 cutval = max_elem;
1330 else
1331 cutval = split_val;
1332
1333 Offset lim1, lim2;
1334 planeSplit(obj, ind, count, cutfeat, cutval, lim1, lim2);
1335
1336 if (lim1 > count / 2)
1337 index = lim1;
1338 else if (lim2 < count / 2)
1339 index = lim2;
1340 else
1341 index = count / 2;
1342 }
1343
1354 const Derived& obj, const Offset ind, const Size count,
1355 const Dimension cutfeat, const DistanceType& cutval, Offset& lim1,
1356 Offset& lim2)
1357 {
1358 /* Move vector indices for left subtree to front of list. */
1359 Offset left = 0;
1360 Offset right = count - 1;
1361 for (;;)
1362 {
1363 while (left <= right &&
1364 dataset_get(obj, vAcc_[ind + left], cutfeat) < cutval)
1365 ++left;
1366 while (right && left <= right &&
1367 dataset_get(obj, vAcc_[ind + right], cutfeat) >= cutval)
1368 --right;
1369 if (left > right || !right)
1370 break; // "!right" was added to support unsigned Index types
1371 std::swap(vAcc_[ind + left], vAcc_[ind + right]);
1372 ++left;
1373 --right;
1374 }
1375 /* If either list is empty, it means that all remaining features
1376 * are identical. Split in the middle to maintain a balanced tree.
1377 */
1378 lim1 = left;
1379 right = count - 1;
1380 for (;;)
1381 {
1382 while (left <= right &&
1383 dataset_get(obj, vAcc_[ind + left], cutfeat) <= cutval)
1384 ++left;
1385 while (right && left <= right &&
1386 dataset_get(obj, vAcc_[ind + right], cutfeat) > cutval)
1387 --right;
1388 if (left > right || !right)
1389 break; // "!right" was added to support unsigned Index types
1390 std::swap(vAcc_[ind + left], vAcc_[ind + right]);
1391 ++left;
1392 --right;
1393 }
1394 lim2 = left;
1395 }
1396
1397 DistanceType computeInitialDistances(
1398 const Derived& obj, const ElementType* vec,
1399 distance_vector_t& dists) const
1400 {
1401 assert(vec);
1402 DistanceType dist = DistanceType();
1403
1404 for (Dimension i = 0; i < (DIM > 0 ? DIM : obj.dim_); ++i)
1405 {
1406 if (vec[i] < obj.root_bbox_[i].low)
1407 {
1408 dists[i] =
1409 obj.distance_.accum_dist(vec[i], obj.root_bbox_[i].low, i);
1410 dist += dists[i];
1411 }
1412 if (vec[i] > obj.root_bbox_[i].high)
1413 {
1414 dists[i] =
1415 obj.distance_.accum_dist(vec[i], obj.root_bbox_[i].high, i);
1416 dist += dists[i];
1417 }
1418 }
1419 return dist;
1420 }
1421
1422 static void save_tree(
1423 const Derived& obj, std::ostream& stream, const NodeConstPtr tree)
1424 {
1425 save_value(stream, *tree);
1426 if (tree->child1 != nullptr) { save_tree(obj, stream, tree->child1); }
1427 if (tree->child2 != nullptr) { save_tree(obj, stream, tree->child2); }
1428 }
1429
1430 static void load_tree(Derived& obj, std::istream& stream, NodePtr& tree)
1431 {
1432 tree = obj.pool_.template allocate<Node>();
1433 load_value(stream, *tree);
1434 if (tree->child1 != nullptr) { load_tree(obj, stream, tree->child1); }
1435 if (tree->child2 != nullptr) { load_tree(obj, stream, tree->child2); }
1436 }
1437
1443 void saveIndex(const Derived& obj, std::ostream& stream) const
1444 {
1445 save_value(stream, obj.size_);
1446 save_value(stream, obj.dim_);
1447 save_value(stream, obj.root_bbox_);
1448 save_value(stream, obj.leaf_max_size_);
1449 save_value(stream, obj.vAcc_);
1450 if (obj.root_node_) save_tree(obj, stream, obj.root_node_);
1451 }
1452
1458 void loadIndex(Derived& obj, std::istream& stream)
1459 {
1460 load_value(stream, obj.size_);
1461 load_value(stream, obj.dim_);
1462 load_value(stream, obj.root_bbox_);
1463 load_value(stream, obj.leaf_max_size_);
1464 load_value(stream, obj.vAcc_);
1465 load_tree(obj, stream, obj.root_node_);
1466 }
1467};
1468
1510template <
1511 typename Distance, class DatasetAdaptor, int32_t DIM = -1,
1512 typename index_t = uint32_t>
1514 : public KDTreeBaseClass<
1515 KDTreeSingleIndexAdaptor<Distance, DatasetAdaptor, DIM, index_t>,
1516 Distance, DatasetAdaptor, DIM, index_t>
1517{
1518 public:
1522 Distance, DatasetAdaptor, DIM, index_t>&) = delete;
1523
1525 const DatasetAdaptor& dataset_;
1526
1527 const KDTreeSingleIndexAdaptorParams indexParams;
1528
1529 Distance distance_;
1530
1531 using Base = typename nanoflann::KDTreeBaseClass<
1533 Distance, DatasetAdaptor, DIM, index_t>,
1534 Distance, DatasetAdaptor, DIM, index_t>;
1535
1536 using Offset = typename Base::Offset;
1537 using Size = typename Base::Size;
1538 using Dimension = typename Base::Dimension;
1539
1540 using ElementType = typename Base::ElementType;
1541 using DistanceType = typename Base::DistanceType;
1542 using IndexType = typename Base::IndexType;
1543
1544 using Node = typename Base::Node;
1545 using NodePtr = Node*;
1546
1547 using Interval = typename Base::Interval;
1548
1551 using BoundingBox = typename Base::BoundingBox;
1552
1555 using distance_vector_t = typename Base::distance_vector_t;
1556
1577 template <class... Args>
1579 const Dimension dimensionality, const DatasetAdaptor& inputData,
1580 const KDTreeSingleIndexAdaptorParams& params, Args&&... args)
1581 : dataset_(inputData),
1582 indexParams(params),
1583 distance_(inputData, std::forward<Args>(args)...)
1584 {
1585 init(dimensionality, params);
1586 }
1587
1588 explicit KDTreeSingleIndexAdaptor(
1589 const Dimension dimensionality, const DatasetAdaptor& inputData,
1590 const KDTreeSingleIndexAdaptorParams& params = {})
1591 : dataset_(inputData), indexParams(params), distance_(inputData)
1592 {
1593 init(dimensionality, params);
1594 }
1595
1596 private:
1597 void init(
1598 const Dimension dimensionality,
1599 const KDTreeSingleIndexAdaptorParams& params)
1600 {
1601 Base::size_ = dataset_.kdtree_get_point_count();
1602 Base::size_at_index_build_ = Base::size_;
1603 Base::dim_ = dimensionality;
1604 if (DIM > 0) Base::dim_ = DIM;
1605 Base::leaf_max_size_ = params.leaf_max_size;
1606 if (params.n_thread_build > 0)
1607 {
1608 Base::n_thread_build_ = params.n_thread_build;
1609 }
1610 else
1611 {
1612 Base::n_thread_build_ =
1613 std::max(std::thread::hardware_concurrency(), 1u);
1614 }
1615
1616 if (!(params.flags &
1617 KDTreeSingleIndexAdaptorFlags::SkipInitialBuildIndex))
1618 {
1619 // Build KD-tree:
1620 buildIndex();
1621 }
1622 }
1623
1624 public:
1629 {
1630 Base::size_ = dataset_.kdtree_get_point_count();
1631 Base::size_at_index_build_ = Base::size_;
1632 init_vind();
1633 this->freeIndex(*this);
1634 Base::size_at_index_build_ = Base::size_;
1635 if (Base::size_ == 0) return;
1636 computeBoundingBox(Base::root_bbox_);
1637 // construct the tree
1638 if (Base::n_thread_build_ == 1)
1639 {
1640 Base::root_node_ =
1641 this->divideTree(*this, 0, Base::size_, Base::root_bbox_);
1642 }
1643 else
1644 {
1645#ifndef NANOFLANN_NO_THREADS
1646 std::atomic<unsigned int> thread_count(0u);
1647 std::mutex mutex;
1648 Base::root_node_ = this->divideTreeConcurrent(
1649 *this, 0, Base::size_, Base::root_bbox_, thread_count, mutex);
1650#else /* NANOFLANN_NO_THREADS */
1651 throw std::runtime_error("Multithreading is disabled");
1652#endif /* NANOFLANN_NO_THREADS */
1653 }
1654 }
1655
1675 template <typename RESULTSET>
1677 RESULTSET& result, const ElementType* vec,
1678 const SearchParameters& searchParams = {}) const
1679 {
1680 assert(vec);
1681 if (this->size(*this) == 0) return false;
1682 if (!Base::root_node_)
1683 throw std::runtime_error(
1684 "[nanoflann] findNeighbors() called before building the "
1685 "index.");
1686 float epsError = 1 + searchParams.eps;
1687
1688 // fixed or variable-sized container (depending on DIM)
1689 distance_vector_t dists;
1690 // Fill it with zeros.
1691 auto zero = static_cast<decltype(result.worstDist())>(0);
1692 assign(dists, (DIM > 0 ? DIM : Base::dim_), zero);
1693 DistanceType dist = this->computeInitialDistances(*this, vec, dists);
1694 searchLevel(result, vec, Base::root_node_, dist, dists, epsError);
1695
1696 if (searchParams.sorted) result.sort();
1697
1698 return result.full();
1699 }
1700
1717 const ElementType* query_point, const Size num_closest,
1718 IndexType* out_indices, DistanceType* out_distances) const
1719 {
1721 resultSet.init(out_indices, out_distances);
1722 findNeighbors(resultSet, query_point);
1723 return resultSet.size();
1724 }
1725
1746 const ElementType* query_point, const DistanceType& radius,
1747 std::vector<ResultItem<IndexType, DistanceType>>& IndicesDists,
1748 const SearchParameters& searchParams = {}) const
1749 {
1751 radius, IndicesDists);
1752 const Size nFound =
1753 radiusSearchCustomCallback(query_point, resultSet, searchParams);
1754 return nFound;
1755 }
1756
1762 template <class SEARCH_CALLBACK>
1764 const ElementType* query_point, SEARCH_CALLBACK& resultSet,
1765 const SearchParameters& searchParams = {}) const
1766 {
1767 findNeighbors(resultSet, query_point, searchParams);
1768 return resultSet.size();
1769 }
1770
1788 const ElementType* query_point, const Size num_closest,
1789 IndexType* out_indices, DistanceType* out_distances,
1790 const DistanceType& radius) const
1791 {
1793 num_closest, radius);
1794 resultSet.init(out_indices, out_distances);
1795 findNeighbors(resultSet, query_point);
1796 return resultSet.size();
1797 }
1798
1801 public:
1805 {
1806 // Create a permutable array of indices to the input vectors.
1807 Base::size_ = dataset_.kdtree_get_point_count();
1808 if (Base::vAcc_.size() != Base::size_) Base::vAcc_.resize(Base::size_);
1809 for (Size i = 0; i < Base::size_; i++) Base::vAcc_[i] = i;
1810 }
1811
1812 void computeBoundingBox(BoundingBox& bbox)
1813 {
1814 const auto dims = (DIM > 0 ? DIM : Base::dim_);
1815 resize(bbox, dims);
1816 if (dataset_.kdtree_get_bbox(bbox))
1817 {
1818 // Done! It was implemented in derived class
1819 }
1820 else
1821 {
1822 const Size N = dataset_.kdtree_get_point_count();
1823 if (!N)
1824 throw std::runtime_error(
1825 "[nanoflann] computeBoundingBox() called but "
1826 "no data points found.");
1827 for (Dimension i = 0; i < dims; ++i)
1828 {
1829 bbox[i].low = bbox[i].high =
1830 this->dataset_get(*this, Base::vAcc_[0], i);
1831 }
1832 for (Offset k = 1; k < N; ++k)
1833 {
1834 for (Dimension i = 0; i < dims; ++i)
1835 {
1836 const auto val =
1837 this->dataset_get(*this, Base::vAcc_[k], i);
1838 if (val < bbox[i].low) bbox[i].low = val;
1839 if (val > bbox[i].high) bbox[i].high = val;
1840 }
1841 }
1842 }
1843 }
1844
1851 template <class RESULTSET>
1853 RESULTSET& result_set, const ElementType* vec, const NodePtr node,
1854 DistanceType mindist, distance_vector_t& dists,
1855 const float epsError) const
1856 {
1857 /* If this is a leaf node, then do check and return. */
1858 if ((node->child1 == nullptr) && (node->child2 == nullptr))
1859 {
1860 DistanceType worst_dist = result_set.worstDist();
1861 for (Offset i = node->node_type.lr.left;
1862 i < node->node_type.lr.right; ++i)
1863 {
1864 const IndexType accessor = Base::vAcc_[i]; // reorder... : i;
1865 DistanceType dist = distance_.evalMetric(
1866 vec, accessor, (DIM > 0 ? DIM : Base::dim_));
1867 if (dist < worst_dist)
1868 {
1869 if (!result_set.addPoint(dist, Base::vAcc_[i]))
1870 {
1871 // the resultset doesn't want to receive any more
1872 // points, we're done searching!
1873 return false;
1874 }
1875 }
1876 }
1877 return true;
1878 }
1879
1880 /* Which child branch should be taken first? */
1881 Dimension idx = node->node_type.sub.divfeat;
1882 ElementType val = vec[idx];
1883 DistanceType diff1 = val - node->node_type.sub.divlow;
1884 DistanceType diff2 = val - node->node_type.sub.divhigh;
1885
1886 NodePtr bestChild;
1887 NodePtr otherChild;
1888 DistanceType cut_dist;
1889 if ((diff1 + diff2) < 0)
1890 {
1891 bestChild = node->child1;
1892 otherChild = node->child2;
1893 cut_dist =
1894 distance_.accum_dist(val, node->node_type.sub.divhigh, idx);
1895 }
1896 else
1897 {
1898 bestChild = node->child2;
1899 otherChild = node->child1;
1900 cut_dist =
1901 distance_.accum_dist(val, node->node_type.sub.divlow, idx);
1902 }
1903
1904 /* Call recursively to search next level down. */
1905 if (!searchLevel(result_set, vec, bestChild, mindist, dists, epsError))
1906 {
1907 // the resultset doesn't want to receive any more points, we're done
1908 // searching!
1909 return false;
1910 }
1911
1912 DistanceType dst = dists[idx];
1913 mindist = mindist + cut_dist - dst;
1914 dists[idx] = cut_dist;
1915 if (mindist * epsError <= result_set.worstDist())
1916 {
1917 if (!searchLevel(
1918 result_set, vec, otherChild, mindist, dists, epsError))
1919 {
1920 // the resultset doesn't want to receive any more points, we're
1921 // done searching!
1922 return false;
1923 }
1924 }
1925 dists[idx] = dst;
1926 return true;
1927 }
1928
1929 public:
1935 void saveIndex(std::ostream& stream) const
1936 {
1937 Base::saveIndex(*this, stream);
1938 }
1939
1945 void loadIndex(std::istream& stream) { Base::loadIndex(*this, stream); }
1946
1947}; // class KDTree
1948
1986template <
1987 typename Distance, class DatasetAdaptor, int32_t DIM = -1,
1988 typename IndexType = uint32_t>
1990 : public KDTreeBaseClass<
1991 KDTreeSingleIndexDynamicAdaptor_<
1992 Distance, DatasetAdaptor, DIM, IndexType>,
1993 Distance, DatasetAdaptor, DIM, IndexType>
1994{
1995 public:
1999 const DatasetAdaptor& dataset_;
2000
2001 KDTreeSingleIndexAdaptorParams index_params_;
2002
2003 std::vector<int>& treeIndex_;
2004
2005 Distance distance_;
2006
2007 using Base = typename nanoflann::KDTreeBaseClass<
2009 Distance, DatasetAdaptor, DIM, IndexType>,
2010 Distance, DatasetAdaptor, DIM, IndexType>;
2011
2012 using ElementType = typename Base::ElementType;
2013 using DistanceType = typename Base::DistanceType;
2014
2015 using Offset = typename Base::Offset;
2016 using Size = typename Base::Size;
2017 using Dimension = typename Base::Dimension;
2018
2019 using Node = typename Base::Node;
2020 using NodePtr = Node*;
2021
2022 using Interval = typename Base::Interval;
2025 using BoundingBox = typename Base::BoundingBox;
2026
2029 using distance_vector_t = typename Base::distance_vector_t;
2030
2047 const Dimension dimensionality, const DatasetAdaptor& inputData,
2048 std::vector<int>& treeIndex,
2049 const KDTreeSingleIndexAdaptorParams& params =
2051 : dataset_(inputData),
2052 index_params_(params),
2053 treeIndex_(treeIndex),
2054 distance_(inputData)
2055 {
2056 Base::size_ = 0;
2057 Base::size_at_index_build_ = 0;
2058 for (auto& v : Base::root_bbox_) v = {};
2059 Base::dim_ = dimensionality;
2060 if (DIM > 0) Base::dim_ = DIM;
2061 Base::leaf_max_size_ = params.leaf_max_size;
2062 if (params.n_thread_build > 0)
2063 {
2064 Base::n_thread_build_ = params.n_thread_build;
2065 }
2066 else
2067 {
2068 Base::n_thread_build_ =
2069 std::max(std::thread::hardware_concurrency(), 1u);
2070 }
2071 }
2072
2075 const KDTreeSingleIndexDynamicAdaptor_& rhs) = default;
2076
2080 {
2082 std::swap(Base::vAcc_, tmp.Base::vAcc_);
2083 std::swap(Base::leaf_max_size_, tmp.Base::leaf_max_size_);
2084 std::swap(index_params_, tmp.index_params_);
2085 std::swap(treeIndex_, tmp.treeIndex_);
2086 std::swap(Base::size_, tmp.Base::size_);
2087 std::swap(Base::size_at_index_build_, tmp.Base::size_at_index_build_);
2088 std::swap(Base::root_node_, tmp.Base::root_node_);
2089 std::swap(Base::root_bbox_, tmp.Base::root_bbox_);
2090 std::swap(Base::pool_, tmp.Base::pool_);
2091 return *this;
2092 }
2093
2098 {
2099 Base::size_ = Base::vAcc_.size();
2100 this->freeIndex(*this);
2101 Base::size_at_index_build_ = Base::size_;
2102 if (Base::size_ == 0) return;
2103 computeBoundingBox(Base::root_bbox_);
2104 // construct the tree
2105 if (Base::n_thread_build_ == 1)
2106 {
2107 Base::root_node_ =
2108 this->divideTree(*this, 0, Base::size_, Base::root_bbox_);
2109 }
2110 else
2111 {
2112#ifndef NANOFLANN_NO_THREADS
2113 std::atomic<unsigned int> thread_count(0u);
2114 std::mutex mutex;
2115 Base::root_node_ = this->divideTreeConcurrent(
2116 *this, 0, Base::size_, Base::root_bbox_, thread_count, mutex);
2117#else /* NANOFLANN_NO_THREADS */
2118 throw std::runtime_error("Multithreading is disabled");
2119#endif /* NANOFLANN_NO_THREADS */
2120 }
2121 }
2122
2146 template <typename RESULTSET>
2148 RESULTSET& result, const ElementType* vec,
2149 const SearchParameters& searchParams = {}) const
2150 {
2151 assert(vec);
2152 if (this->size(*this) == 0) return false;
2153 if (!Base::root_node_) return false;
2154 float epsError = 1 + searchParams.eps;
2155
2156 // fixed or variable-sized container (depending on DIM)
2157 distance_vector_t dists;
2158 // Fill it with zeros.
2159 assign(
2160 dists, (DIM > 0 ? DIM : Base::dim_),
2161 static_cast<typename distance_vector_t::value_type>(0));
2162 DistanceType dist = this->computeInitialDistances(*this, vec, dists);
2163 searchLevel(result, vec, Base::root_node_, dist, dists, epsError);
2164 return result.full();
2165 }
2166
2182 const ElementType* query_point, const Size num_closest,
2183 IndexType* out_indices, DistanceType* out_distances,
2184 const SearchParameters& searchParams = {}) const
2185 {
2187 resultSet.init(out_indices, out_distances);
2188 findNeighbors(resultSet, query_point, searchParams);
2189 return resultSet.size();
2190 }
2191
2212 const ElementType* query_point, const DistanceType& radius,
2213 std::vector<ResultItem<IndexType, DistanceType>>& IndicesDists,
2214 const SearchParameters& searchParams = {}) const
2215 {
2217 radius, IndicesDists);
2218 const size_t nFound =
2219 radiusSearchCustomCallback(query_point, resultSet, searchParams);
2220 return nFound;
2221 }
2222
2228 template <class SEARCH_CALLBACK>
2230 const ElementType* query_point, SEARCH_CALLBACK& resultSet,
2231 const SearchParameters& searchParams = {}) const
2232 {
2233 findNeighbors(resultSet, query_point, searchParams);
2234 return resultSet.size();
2235 }
2236
2239 public:
2240 void computeBoundingBox(BoundingBox& bbox)
2241 {
2242 const auto dims = (DIM > 0 ? DIM : Base::dim_);
2243 resize(bbox, dims);
2244
2245 if (dataset_.kdtree_get_bbox(bbox))
2246 {
2247 // Done! It was implemented in derived class
2248 }
2249 else
2250 {
2251 const Size N = Base::size_;
2252 if (!N)
2253 throw std::runtime_error(
2254 "[nanoflann] computeBoundingBox() called but "
2255 "no data points found.");
2256 for (Dimension i = 0; i < dims; ++i)
2257 {
2258 bbox[i].low = bbox[i].high =
2259 this->dataset_get(*this, Base::vAcc_[0], i);
2260 }
2261 for (Offset k = 1; k < N; ++k)
2262 {
2263 for (Dimension i = 0; i < dims; ++i)
2264 {
2265 const auto val =
2266 this->dataset_get(*this, Base::vAcc_[k], i);
2267 if (val < bbox[i].low) bbox[i].low = val;
2268 if (val > bbox[i].high) bbox[i].high = val;
2269 }
2270 }
2271 }
2272 }
2273
2278 template <class RESULTSET>
2280 RESULTSET& result_set, const ElementType* vec, const NodePtr node,
2281 DistanceType mindist, distance_vector_t& dists,
2282 const float epsError) const
2283 {
2284 /* If this is a leaf node, then do check and return. */
2285 if ((node->child1 == nullptr) && (node->child2 == nullptr))
2286 {
2287 DistanceType worst_dist = result_set.worstDist();
2288 for (Offset i = node->node_type.lr.left;
2289 i < node->node_type.lr.right; ++i)
2290 {
2291 const IndexType index = Base::vAcc_[i]; // reorder... : i;
2292 if (treeIndex_[index] == -1) continue;
2293 DistanceType dist = distance_.evalMetric(
2294 vec, index, (DIM > 0 ? DIM : Base::dim_));
2295 if (dist < worst_dist)
2296 {
2297 if (!result_set.addPoint(
2298 static_cast<typename RESULTSET::DistanceType>(dist),
2299 static_cast<typename RESULTSET::IndexType>(
2300 Base::vAcc_[i])))
2301 {
2302 // the resultset doesn't want to receive any more
2303 // points, we're done searching!
2304 return; // false;
2305 }
2306 }
2307 }
2308 return;
2309 }
2310
2311 /* Which child branch should be taken first? */
2312 Dimension idx = node->node_type.sub.divfeat;
2313 ElementType val = vec[idx];
2314 DistanceType diff1 = val - node->node_type.sub.divlow;
2315 DistanceType diff2 = val - node->node_type.sub.divhigh;
2316
2317 NodePtr bestChild;
2318 NodePtr otherChild;
2319 DistanceType cut_dist;
2320 if ((diff1 + diff2) < 0)
2321 {
2322 bestChild = node->child1;
2323 otherChild = node->child2;
2324 cut_dist =
2325 distance_.accum_dist(val, node->node_type.sub.divhigh, idx);
2326 }
2327 else
2328 {
2329 bestChild = node->child2;
2330 otherChild = node->child1;
2331 cut_dist =
2332 distance_.accum_dist(val, node->node_type.sub.divlow, idx);
2333 }
2334
2335 /* Call recursively to search next level down. */
2336 searchLevel(result_set, vec, bestChild, mindist, dists, epsError);
2337
2338 DistanceType dst = dists[idx];
2339 mindist = mindist + cut_dist - dst;
2340 dists[idx] = cut_dist;
2341 if (mindist * epsError <= result_set.worstDist())
2342 {
2343 searchLevel(result_set, vec, otherChild, mindist, dists, epsError);
2344 }
2345 dists[idx] = dst;
2346 }
2347
2348 public:
2354 void saveIndex(std::ostream& stream) { saveIndex(*this, stream); }
2355
2361 void loadIndex(std::istream& stream) { loadIndex(*this, stream); }
2362};
2363
2378template <
2379 typename Distance, class DatasetAdaptor, int32_t DIM = -1,
2380 typename IndexType = uint32_t>
2382{
2383 public:
2384 using ElementType = typename Distance::ElementType;
2385 using DistanceType = typename Distance::DistanceType;
2386
2387 using Offset = typename KDTreeSingleIndexDynamicAdaptor_<
2388 Distance, DatasetAdaptor, DIM>::Offset;
2389 using Size = typename KDTreeSingleIndexDynamicAdaptor_<
2390 Distance, DatasetAdaptor, DIM>::Size;
2391 using Dimension = typename KDTreeSingleIndexDynamicAdaptor_<
2392 Distance, DatasetAdaptor, DIM>::Dimension;
2393
2394 protected:
2395 Size leaf_max_size_;
2396 Size treeCount_;
2397 Size pointCount_;
2398
2402 const DatasetAdaptor& dataset_;
2403
2406 std::vector<int> treeIndex_;
2407 std::unordered_set<int> removedPoints_;
2408
2409 KDTreeSingleIndexAdaptorParams index_params_;
2410
2411 Dimension dim_;
2412
2414 Distance, DatasetAdaptor, DIM, IndexType>;
2415 std::vector<index_container_t> index_;
2416
2417 public:
2420 const std::vector<index_container_t>& getAllIndices() const
2421 {
2422 return index_;
2423 }
2424
2425 private:
2427 int First0Bit(IndexType num)
2428 {
2429 int pos = 0;
2430 while (num & 1)
2431 {
2432 num = num >> 1;
2433 pos++;
2434 }
2435 return pos;
2436 }
2437
2439 void init()
2440 {
2441 using my_kd_tree_t = KDTreeSingleIndexDynamicAdaptor_<
2442 Distance, DatasetAdaptor, DIM, IndexType>;
2443 std::vector<my_kd_tree_t> index(
2444 treeCount_,
2445 my_kd_tree_t(dim_ /*dim*/, dataset_, treeIndex_, index_params_));
2446 index_ = index;
2447 }
2448
2449 public:
2450 Distance distance_;
2451
2468 const int dimensionality, const DatasetAdaptor& inputData,
2469 const KDTreeSingleIndexAdaptorParams& params =
2471 const size_t maximumPointCount = 1000000000U)
2472 : dataset_(inputData), index_params_(params), distance_(inputData)
2473 {
2474 treeCount_ = static_cast<size_t>(std::log2(maximumPointCount)) + 1;
2475 pointCount_ = 0U;
2476 dim_ = dimensionality;
2477 treeIndex_.clear();
2478 if (DIM > 0) dim_ = DIM;
2479 leaf_max_size_ = params.leaf_max_size;
2480 init();
2481 const size_t num_initial_points = dataset_.kdtree_get_point_count();
2482 if (num_initial_points > 0) { addPoints(0, num_initial_points - 1); }
2483 }
2484
2488 Distance, DatasetAdaptor, DIM, IndexType>&) = delete;
2489
2491 void addPoints(IndexType start, IndexType end)
2492 {
2493 const Size count = end - start + 1;
2494 int maxIndex = 0;
2495 treeIndex_.resize(treeIndex_.size() + count);
2496 for (IndexType idx = start; idx <= end; idx++)
2497 {
2498 const int pos = First0Bit(pointCount_);
2499 maxIndex = std::max(pos, maxIndex);
2500 treeIndex_[pointCount_] = pos;
2501
2502 const auto it = removedPoints_.find(idx);
2503 if (it != removedPoints_.end())
2504 {
2505 removedPoints_.erase(it);
2506 treeIndex_[idx] = pos;
2507 }
2508
2509 for (int i = 0; i < pos; i++)
2510 {
2511 for (int j = 0; j < static_cast<int>(index_[i].vAcc_.size());
2512 j++)
2513 {
2514 index_[pos].vAcc_.push_back(index_[i].vAcc_[j]);
2515 if (treeIndex_[index_[i].vAcc_[j]] != -1)
2516 treeIndex_[index_[i].vAcc_[j]] = pos;
2517 }
2518 index_[i].vAcc_.clear();
2519 }
2520 index_[pos].vAcc_.push_back(idx);
2521 pointCount_++;
2522 }
2523
2524 for (int i = 0; i <= maxIndex; ++i)
2525 {
2526 index_[i].freeIndex(index_[i]);
2527 if (!index_[i].vAcc_.empty()) index_[i].buildIndex();
2528 }
2529 }
2530
2532 void removePoint(size_t idx)
2533 {
2534 if (idx >= pointCount_) return;
2535 removedPoints_.insert(idx);
2536 treeIndex_[idx] = -1;
2537 }
2538
2555 template <typename RESULTSET>
2557 RESULTSET& result, const ElementType* vec,
2558 const SearchParameters& searchParams = {}) const
2559 {
2560 for (size_t i = 0; i < treeCount_; i++)
2561 {
2562 index_[i].findNeighbors(result, &vec[0], searchParams);
2563 }
2564 return result.full();
2565 }
2566};
2567
2593template <
2594 class MatrixType, int32_t DIM = -1, class Distance = nanoflann::metric_L2,
2595 bool row_major = true>
2597{
2598 using self_t =
2600 using num_t = typename MatrixType::Scalar;
2601 using IndexType = typename MatrixType::Index;
2602 using metric_t = typename Distance::template traits<
2603 num_t, self_t, IndexType>::distance_t;
2604
2606 metric_t, self_t,
2607 row_major ? MatrixType::ColsAtCompileTime
2608 : MatrixType::RowsAtCompileTime,
2609 IndexType>;
2610
2611 index_t* index_;
2613
2614 using Offset = typename index_t::Offset;
2615 using Size = typename index_t::Size;
2616 using Dimension = typename index_t::Dimension;
2617
2620 const Dimension dimensionality,
2621 const std::reference_wrapper<const MatrixType>& mat,
2622 const int leaf_max_size = 10, const unsigned int n_thread_build = 1)
2623 : m_data_matrix(mat)
2624 {
2625 const auto dims = row_major ? mat.get().cols() : mat.get().rows();
2626 if (static_cast<Dimension>(dims) != dimensionality)
2627 throw std::runtime_error(
2628 "Error: 'dimensionality' must match column count in data "
2629 "matrix");
2630 if (DIM > 0 && static_cast<int32_t>(dims) != DIM)
2631 throw std::runtime_error(
2632 "Data set dimensionality does not match the 'DIM' template "
2633 "argument");
2634 index_ = new index_t(
2635 dims, *this /* adaptor */,
2637 leaf_max_size, nanoflann::KDTreeSingleIndexAdaptorFlags::None,
2638 n_thread_build));
2639 }
2640
2641 public:
2644
2645 ~KDTreeEigenMatrixAdaptor() { delete index_; }
2646
2647 const std::reference_wrapper<const MatrixType> m_data_matrix;
2648
2657 void query(
2658 const num_t* query_point, const Size num_closest,
2659 IndexType* out_indices, num_t* out_distances) const
2660 {
2661 nanoflann::KNNResultSet<num_t, IndexType> resultSet(num_closest);
2662 resultSet.init(out_indices, out_distances);
2663 index_->findNeighbors(resultSet, query_point);
2664 }
2665
2669 const self_t& derived() const { return *this; }
2670 self_t& derived() { return *this; }
2671
2672 // Must return the number of data points
2673 Size kdtree_get_point_count() const
2674 {
2675 if (row_major)
2676 return m_data_matrix.get().rows();
2677 else
2678 return m_data_matrix.get().cols();
2679 }
2680
2681 // Returns the dim'th component of the idx'th point in the class:
2682 num_t kdtree_get_pt(const IndexType idx, size_t dim) const
2683 {
2684 if (row_major)
2685 return m_data_matrix.get().coeff(idx, IndexType(dim));
2686 else
2687 return m_data_matrix.get().coeff(IndexType(dim), idx);
2688 }
2689
2690 // Optional bounding-box computation: return false to default to a standard
2691 // bbox computation loop.
2692 // Return true if the BBOX was already computed by the class and returned
2693 // in "bb" so it can be avoided to redo it again. Look at bb.size() to
2694 // find out the expected dimensionality (e.g. 2 or 3 for point clouds)
2695 template <class BBOX>
2696 bool kdtree_get_bbox(BBOX& /*bb*/) const
2697 {
2698 return false;
2699 }
2700
2703}; // end of KDTreeEigenMatrixAdaptor
// end of grouping
2707} // namespace nanoflann
Definition nanoflann.hpp:1001
void freeIndex(Derived &obj)
Definition nanoflann.hpp:1005
BoundingBox root_bbox_
Definition nanoflann.hpp:1079
Size veclen(const Derived &obj)
Definition nanoflann.hpp:1094
void saveIndex(const Derived &obj, std::ostream &stream) const
Definition nanoflann.hpp:1443
Size usedMemory(Derived &obj)
Definition nanoflann.hpp:1107
typename array_or_vector< DIM, DistanceType >::type distance_vector_t
Definition nanoflann.hpp:1076
void planeSplit(const Derived &obj, const Offset ind, const Size count, const Dimension cutfeat, const DistanceType &cutval, Offset &lim1, Offset &lim2)
Definition nanoflann.hpp:1353
NodePtr divideTree(Derived &obj, const Offset left, const Offset right, BoundingBox &bbox)
Definition nanoflann.hpp:1135
std::vector< IndexType > vAcc_
Definition nanoflann.hpp:1019
Size size(const Derived &obj) const
Definition nanoflann.hpp:1091
NodePtr divideTreeConcurrent(Derived &obj, const Offset left, const Offset right, BoundingBox &bbox, std::atomic< unsigned int > &thread_count, std::mutex &mutex)
Definition nanoflann.hpp:1204
void loadIndex(Derived &obj, std::istream &stream)
Definition nanoflann.hpp:1458
PooledAllocator pool_
Definition nanoflann.hpp:1088
ElementType dataset_get(const Derived &obj, IndexType element, Dimension component) const
Helper accessor to the dataset points:
Definition nanoflann.hpp:1097
typename array_or_vector< DIM, Interval >::type BoundingBox
Definition nanoflann.hpp:1072
Definition nanoflann.hpp:1517
bool searchLevel(RESULTSET &result_set, const ElementType *vec, const NodePtr node, DistanceType mindist, distance_vector_t &dists, const float epsError) const
Definition nanoflann.hpp:1852
void saveIndex(std::ostream &stream) const
Definition nanoflann.hpp:1935
Size radiusSearch(const ElementType *query_point, const DistanceType &radius, std::vector< ResultItem< IndexType, DistanceType > > &IndicesDists, const SearchParameters &searchParams={}) const
Definition nanoflann.hpp:1745
void init_vind()
Definition nanoflann.hpp:1804
void buildIndex()
Definition nanoflann.hpp:1628
const DatasetAdaptor & dataset_
Definition nanoflann.hpp:1525
KDTreeSingleIndexAdaptor(const KDTreeSingleIndexAdaptor< Distance, DatasetAdaptor, DIM, index_t > &)=delete
bool findNeighbors(RESULTSET &result, const ElementType *vec, const SearchParameters &searchParams={}) const
Definition nanoflann.hpp:1676
Size rknnSearch(const ElementType *query_point, const Size num_closest, IndexType *out_indices, DistanceType *out_distances, const DistanceType &radius) const
Definition nanoflann.hpp:1787
Size radiusSearchCustomCallback(const ElementType *query_point, SEARCH_CALLBACK &resultSet, const SearchParameters &searchParams={}) const
Definition nanoflann.hpp:1763
typename Base::distance_vector_t distance_vector_t
Definition nanoflann.hpp:1555
void loadIndex(std::istream &stream)
Definition nanoflann.hpp:1945
typename Base::BoundingBox BoundingBox
Definition nanoflann.hpp:1551
KDTreeSingleIndexAdaptor(const Dimension dimensionality, const DatasetAdaptor &inputData, const KDTreeSingleIndexAdaptorParams &params, Args &&... args)
Definition nanoflann.hpp:1578
Size knnSearch(const ElementType *query_point, const Size num_closest, IndexType *out_indices, DistanceType *out_distances) const
Definition nanoflann.hpp:1716
Definition nanoflann.hpp:1994
Size radiusSearch(const ElementType *query_point, const DistanceType &radius, std::vector< ResultItem< IndexType, DistanceType > > &IndicesDists, const SearchParameters &searchParams={}) const
Definition nanoflann.hpp:2211
KDTreeSingleIndexDynamicAdaptor_(const Dimension dimensionality, const DatasetAdaptor &inputData, std::vector< int > &treeIndex, const KDTreeSingleIndexAdaptorParams &params=KDTreeSingleIndexAdaptorParams())
Definition nanoflann.hpp:2046
typename Base::BoundingBox BoundingBox
Definition nanoflann.hpp:2025
const DatasetAdaptor & dataset_
The source of our data.
Definition nanoflann.hpp:1999
Size radiusSearchCustomCallback(const ElementType *query_point, SEARCH_CALLBACK &resultSet, const SearchParameters &searchParams={}) const
Definition nanoflann.hpp:2229
KDTreeSingleIndexDynamicAdaptor_(const KDTreeSingleIndexDynamicAdaptor_ &rhs)=default
void buildIndex()
Definition nanoflann.hpp:2097
void saveIndex(std::ostream &stream)
Definition nanoflann.hpp:2354
typename Base::distance_vector_t distance_vector_t
Definition nanoflann.hpp:2029
void loadIndex(std::istream &stream)
Definition nanoflann.hpp:2361
Size knnSearch(const ElementType *query_point, const Size num_closest, IndexType *out_indices, DistanceType *out_distances, const SearchParameters &searchParams={}) const
Definition nanoflann.hpp:2181
void searchLevel(RESULTSET &result_set, const ElementType *vec, const NodePtr node, DistanceType mindist, distance_vector_t &dists, const float epsError) const
Definition nanoflann.hpp:2279
bool findNeighbors(RESULTSET &result, const ElementType *vec, const SearchParameters &searchParams={}) const
Definition nanoflann.hpp:2147
KDTreeSingleIndexDynamicAdaptor_ operator=(const KDTreeSingleIndexDynamicAdaptor_ &rhs)
Definition nanoflann.hpp:2078
Definition nanoflann.hpp:2382
bool findNeighbors(RESULTSET &result, const ElementType *vec, const SearchParameters &searchParams={}) const
Definition nanoflann.hpp:2556
const DatasetAdaptor & dataset_
The source of our data.
Definition nanoflann.hpp:2402
void removePoint(size_t idx)
Definition nanoflann.hpp:2532
void addPoints(IndexType start, IndexType end)
Definition nanoflann.hpp:2491
KDTreeSingleIndexDynamicAdaptor(const int dimensionality, const DatasetAdaptor &inputData, const KDTreeSingleIndexAdaptorParams &params=KDTreeSingleIndexAdaptorParams(), const size_t maximumPointCount=1000000000U)
Definition nanoflann.hpp:2467
std::vector< int > treeIndex_
Definition nanoflann.hpp:2406
const std::vector< index_container_t > & getAllIndices() const
Definition nanoflann.hpp:2420
Dimension dim_
Dimensionality of each data point.
Definition nanoflann.hpp:2411
KDTreeSingleIndexDynamicAdaptor(const KDTreeSingleIndexDynamicAdaptor< Distance, DatasetAdaptor, DIM, IndexType > &)=delete
Definition nanoflann.hpp:200
bool addPoint(DistanceType dist, IndexType index)
Definition nanoflann.hpp:236
Definition nanoflann.hpp:849
~PooledAllocator()
Definition nanoflann.hpp:885
void free_all()
Definition nanoflann.hpp:888
void * malloc(const size_t req_size)
Definition nanoflann.hpp:904
T * allocate(const size_t count=1)
Definition nanoflann.hpp:955
PooledAllocator()
Definition nanoflann.hpp:880
Definition nanoflann.hpp:284
bool addPoint(DistanceType dist, IndexType index)
Definition nanoflann.hpp:325
Definition nanoflann.hpp:373
ResultItem< IndexType, DistanceType > worst_item() const
Definition nanoflann.hpp:416
bool addPoint(DistanceType dist, IndexType index)
Definition nanoflann.hpp:404
std::enable_if< has_assign< Container >::value, void >::type assign(Container &c, const size_t nElements, const T &value)
Definition nanoflann.hpp:144
T pi_const()
Definition nanoflann.hpp:87
std::enable_if< has_resize< Container >::value, void >::type resize(Container &c, const size_t nElements)
Definition nanoflann.hpp:122
Definition nanoflann.hpp:162
bool operator()(const PairType &p1, const PairType &p2) const
Definition nanoflann.hpp:165
Definition nanoflann.hpp:1054
Definition nanoflann.hpp:1029
DistanceType divlow
The values used for subdivision.
Definition nanoflann.hpp:1042
Offset right
Indices of points in leaf node.
Definition nanoflann.hpp:1036
union nanoflann::KDTreeBaseClass::Node::@0 node_type
Dimension divfeat
Definition nanoflann.hpp:1040
Node * child1
Definition nanoflann.hpp:1047
Definition nanoflann.hpp:2597
void query(const num_t *query_point, const Size num_closest, IndexType *out_indices, num_t *out_distances) const
Definition nanoflann.hpp:2657
KDTreeEigenMatrixAdaptor(const self_t &)=delete
typename index_t::Offset Offset
Definition nanoflann.hpp:2614
KDTreeEigenMatrixAdaptor(const Dimension dimensionality, const std::reference_wrapper< const MatrixType > &mat, const int leaf_max_size=10, const unsigned int n_thread_build=1)
Constructor: takes a const ref to the matrix object with the data points.
Definition nanoflann.hpp:2619
Definition nanoflann.hpp:800
Definition nanoflann.hpp:489
Definition nanoflann.hpp:551
Definition nanoflann.hpp:616
Definition nanoflann.hpp:472
Definition nanoflann.hpp:181
DistanceType second
Distance from sample to query point.
Definition nanoflann.hpp:189
IndexType first
Index of the sample in the dataset.
Definition nanoflann.hpp:188
Definition nanoflann.hpp:661
DistanceType accum_dist(const U a, const V b, const size_t) const
Definition nanoflann.hpp:679
Definition nanoflann.hpp:706
Definition nanoflann.hpp:819
bool sorted
distance (default: true)
Definition nanoflann.hpp:826
float eps
search for eps-approximate neighbours (default: 0)
Definition nanoflann.hpp:825
Definition nanoflann.hpp:971
Definition nanoflann.hpp:109
Definition nanoflann.hpp:98
Definition nanoflann.hpp:736
Definition nanoflann.hpp:733
Definition nanoflann.hpp:746
Definition nanoflann.hpp:756
Definition nanoflann.hpp:753
Definition nanoflann.hpp:743
Definition nanoflann.hpp:765
Definition nanoflann.hpp:762
Definition nanoflann.hpp:774
Definition nanoflann.hpp:771