heap.h 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. *
  7. * THE BSD LICENSE
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in the
  17. * documentation and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  20. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  21. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  22. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  23. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  24. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  28. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *************************************************************************/
  30. #ifndef OPENCV_FLANN_HEAP_H_
  31. #define OPENCV_FLANN_HEAP_H_
  32. //! @cond IGNORED
  33. #include <algorithm>
  34. #include <vector>
  35. #include <unordered_map>
  36. namespace cvflann
  37. {
  38. // TODO: Define x > y operator and use std::greater<T> instead
  39. template <typename T>
  40. struct greater
  41. {
  42. bool operator()(const T& x, const T& y) const
  43. {
  44. return y < x;
  45. }
  46. };
  47. /**
  48. * Priority Queue Implementation
  49. *
  50. * The priority queue is implemented with a heap. A heap is a complete
  51. * (full) binary tree in which each parent is less than both of its
  52. * children, but the order of the children is unspecified.
  53. */
  54. template <typename T>
  55. class Heap
  56. {
  57. /**
  58. * Storage array for the heap.
  59. * Type T must be comparable.
  60. */
  61. std::vector<T> heap;
  62. public:
  63. /**
  64. * \brief Constructs a heap with a pre-allocated capacity
  65. *
  66. * \param capacity heap maximum capacity
  67. */
  68. Heap(const int capacity)
  69. {
  70. reserve(capacity);
  71. }
  72. /**
  73. * \brief Move-constructs a heap from an external vector
  74. *
  75. * \param vec external vector
  76. */
  77. Heap(std::vector<T>&& vec)
  78. : heap(std::move(vec))
  79. {
  80. std::make_heap(heap.begin(), heap.end(), greater<T>());
  81. }
  82. /**
  83. *
  84. * \returns heap size
  85. */
  86. int size() const
  87. {
  88. return (int)heap.size();
  89. }
  90. /**
  91. *
  92. * \returns heap capacity
  93. */
  94. int capacity() const
  95. {
  96. return (int)heap.capacity();
  97. }
  98. /**
  99. * \brief Tests if the heap is empty
  100. *
  101. * \returns true is heap empty, false otherwise
  102. */
  103. bool empty()
  104. {
  105. return heap.empty();
  106. }
  107. /**
  108. * \brief Clears the heap.
  109. */
  110. void clear()
  111. {
  112. heap.clear();
  113. }
  114. /**
  115. * \brief Sets the heap maximum capacity.
  116. *
  117. * \param capacity heap maximum capacity
  118. */
  119. void reserve(const int capacity)
  120. {
  121. heap.reserve(capacity);
  122. }
  123. /**
  124. * \brief Inserts a new element in the heap.
  125. *
  126. * We select the next empty leaf node, and then keep moving any larger
  127. * parents down until the right location is found to store this element.
  128. *
  129. * \param value the new element to be inserted in the heap
  130. */
  131. void insert(T value)
  132. {
  133. /* If heap is full, then return without adding this element. */
  134. if (size() == capacity()) {
  135. return;
  136. }
  137. heap.push_back(value);
  138. std::push_heap(heap.begin(), heap.end(), greater<T>());
  139. }
  140. /**
  141. * \brief Returns the node of minimum value from the heap (top of the heap).
  142. *
  143. * \param[out] value parameter used to return the min element
  144. * \returns false if heap empty
  145. */
  146. bool popMin(T& value)
  147. {
  148. if (empty()) {
  149. return false;
  150. }
  151. value = heap[0];
  152. std::pop_heap(heap.begin(), heap.end(), greater<T>());
  153. heap.pop_back();
  154. return true; /* Return old last node. */
  155. }
  156. /**
  157. * \brief Returns a shared heap for the given memory pool ID.
  158. *
  159. * It constructs the heap if it does not already exists.
  160. *
  161. * \param poolId a user-chosen hashable ID for identifying the heap.
  162. * For thread-safe operations, using current thread ID is a good choice.
  163. * \param capacity heap maximum capacity
  164. * \param iterThreshold remove heaps that were not reused for more than specified iterations count
  165. * if iterThreshold value is less 2, it will be internally adjusted to twice the number of CPU threads
  166. * \returns pointer to the heap
  167. */
  168. template <typename HashableT>
  169. static cv::Ptr<Heap<T>> getPooledInstance(
  170. const HashableT& poolId, const int capacity, int iterThreshold = 0)
  171. {
  172. static cv::Mutex mutex;
  173. const cv::AutoLock lock(mutex);
  174. struct HeapMapValueType {
  175. cv::Ptr<Heap<T>> heapPtr;
  176. int iterCounter;
  177. };
  178. typedef std::unordered_map<HashableT, HeapMapValueType> HeapMapType;
  179. static HeapMapType heapsPool;
  180. typename HeapMapType::iterator heapIt = heapsPool.find(poolId);
  181. if (heapIt == heapsPool.end())
  182. {
  183. // Construct the heap as it does not already exists
  184. HeapMapValueType heapAndTimePair = {cv::makePtr<Heap<T>>(capacity), 0};
  185. const std::pair<typename HeapMapType::iterator, bool>& emplaceResult = heapsPool.emplace(poolId, std::move(heapAndTimePair));
  186. CV_CheckEQ(static_cast<int>(emplaceResult.second), 1, "Failed to insert the heap into its memory pool");
  187. heapIt = emplaceResult.first;
  188. }
  189. else
  190. {
  191. CV_CheckEQ(heapIt->second.heapPtr.use_count(), 1, "Cannot modify a heap that is currently accessed by another caller");
  192. heapIt->second.heapPtr->clear();
  193. heapIt->second.heapPtr->reserve(capacity);
  194. heapIt->second.iterCounter = 0;
  195. }
  196. if (iterThreshold <= 1) {
  197. iterThreshold = 2 * cv::getNumThreads();
  198. }
  199. // Remove heaps that were not reused for more than given iterThreshold
  200. typename HeapMapType::iterator cleanupIt = heapsPool.begin();
  201. while (cleanupIt != heapsPool.end())
  202. {
  203. if (cleanupIt->second.iterCounter++ > iterThreshold)
  204. {
  205. CV_Assert(cleanupIt != heapIt);
  206. cleanupIt = heapsPool.erase(cleanupIt);
  207. continue;
  208. }
  209. ++cleanupIt;
  210. }
  211. return heapIt->second.heapPtr;
  212. }
  213. };
  214. }
  215. //! @endcond
  216. #endif //OPENCV_FLANN_HEAP_H_