KDTreeVectorOfVectorsAdaptor.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /***********************************************************************
  2. * Software License Agreement (BSD License)
  3. *
  4. * Copyright 2011-16 Jose Luis Blanco (joseluisblancoc@gmail.com).
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  18. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  19. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  20. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  21. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  22. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. *************************************************************************/
  28. #pragma once
  29. #include <nanoflann.hpp>
  30. #include <vector>
  31. // ===== This example shows how to use nanoflann with these types of containers:
  32. // using my_vector_of_vectors_t = std::vector<std::vector<double> > ;
  33. //
  34. // The next one requires #include <Eigen/Dense>
  35. // using my_vector_of_vectors_t = std::vector<Eigen::VectorXd> ;
  36. // =============================================================================
  37. /** A simple vector-of-vectors adaptor for nanoflann, without duplicating the
  38. * storage. The i'th vector represents a point in the state space.
  39. *
  40. * \tparam DIM If set to >0, it specifies a compile-time fixed dimensionality
  41. * for the points in the data set, allowing more compiler optimizations.
  42. * \tparam num_t The type of the point coordinates (typ. double or float).
  43. * \tparam Distance The distance metric to use: nanoflann::metric_L1,
  44. * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc.
  45. * \tparam IndexType The type for indices in the KD-tree index
  46. * (typically, size_t of int)
  47. */
  48. template <
  49. class VectorOfVectorsType, typename num_t = double, int DIM = -1,
  50. class Distance = nanoflann::metric_L2, typename IndexType = size_t>
  51. struct KDTreeVectorOfVectorsAdaptor
  52. {
  53. using self_t = KDTreeVectorOfVectorsAdaptor<
  54. VectorOfVectorsType, num_t, DIM, Distance, IndexType>;
  55. using metric_t =
  56. typename Distance::template traits<num_t, self_t>::distance_t;
  57. using index_t =
  58. nanoflann::KDTreeSingleIndexAdaptor<metric_t, self_t, DIM, IndexType>;
  59. /** The kd-tree index for the user to call its methods as usual with any
  60. * other FLANN index */
  61. index_t* index = nullptr;
  62. /// Constructor: takes a const ref to the vector of vectors object with the
  63. /// data points
  64. KDTreeVectorOfVectorsAdaptor(
  65. const size_t /* dimensionality */, const VectorOfVectorsType& mat,
  66. const int leaf_max_size = 10, const unsigned int n_thread_build = 1)
  67. : m_data(mat)
  68. {
  69. assert(mat.size() != 0 && mat[0].size() != 0);
  70. const size_t dims = mat[0].size();
  71. if (DIM > 0 && static_cast<int>(dims) != DIM)
  72. throw std::runtime_error(
  73. "Data set dimensionality does not match the 'DIM' template "
  74. "argument");
  75. index = new index_t(
  76. static_cast<int>(dims), *this /* adaptor */,
  77. nanoflann::KDTreeSingleIndexAdaptorParams(
  78. leaf_max_size, nanoflann::KDTreeSingleIndexAdaptorFlags::None,
  79. n_thread_build));
  80. }
  81. ~KDTreeVectorOfVectorsAdaptor() { delete index; }
  82. const VectorOfVectorsType& m_data;
  83. /** Query for the \a num_closest closest points to a given point
  84. * (entered as query_point[0:dim-1]).
  85. * Note that this is a short-cut method for index->findNeighbors().
  86. * The user can also call index->... methods as desired.
  87. */
  88. inline void query(
  89. const num_t* query_point, const size_t num_closest,
  90. IndexType* out_indices, num_t* out_distances_sq) const
  91. {
  92. nanoflann::KNNResultSet<num_t, IndexType> resultSet(num_closest);
  93. resultSet.init(out_indices, out_distances_sq);
  94. index->findNeighbors(resultSet, query_point);
  95. }
  96. /** @name Interface expected by KDTreeSingleIndexAdaptor
  97. * @{ */
  98. const self_t& derived() const { return *this; }
  99. self_t& derived() { return *this; }
  100. // Must return the number of data points
  101. inline size_t kdtree_get_point_count() const { return m_data.size(); }
  102. // Returns the dim'th component of the idx'th point in the class:
  103. inline num_t kdtree_get_pt(const size_t idx, const size_t dim) const
  104. {
  105. return m_data[idx][dim];
  106. }
  107. // Optional bounding-box computation: return false to default to a standard
  108. // bbox computation loop.
  109. // Return true if the BBOX was already computed by the class and returned
  110. // in "bb" so it can be avoided to redo it again. Look at bb.size() to
  111. // find out the expected dimensionality (e.g. 2 or 3 for point clouds)
  112. template <class BBOX>
  113. bool kdtree_get_bbox(BBOX& /*bb*/) const
  114. {
  115. return false;
  116. }
  117. /** @} */
  118. }; // end of KDTreeVectorOfVectorsAdaptor