You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1082 lines
35 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /** @file kdtree.c
  2. ** @brief KD-tree - Definition
  3. ** @author Andrea Vedaldi, David Novotny
  4. **/
  5. /*
  6. Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
  7. All rights reserved.
  8. This file is part of the VLFeat library and is made available under
  9. the terms of the BSD license (see the COPYING file).
  10. */
  11. /**
  12. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  13. @page kdtree KD-trees and forests
  14. @author Andrea Vedaldi
  15. @author David Novotny
  16. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  17. @ref kdtree.h implements a KD-tree object, a data structure that can
  18. efficiently index moderately dimensional vector spaces. Both
  19. best-bin-first @cite{beis97shape} and randomized KD-tree forests are
  20. implemented
  21. @cite{silpa-anan08optimised},@cite{muja09fast}. Applications include
  22. fast matching of feature descriptors.
  23. - @ref kdtree-overview
  24. - @ref kdtree-tech
  25. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  26. @section kdtree-overview Overview
  27. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  28. To create a ::VlKDForest object use ::vl_kdforest_new specifying the
  29. dimensionality of the data and the number of trees in the forest.
  30. With one tree only, the algorithm is analogous to @cite{beis97shape}
  31. (best-bin KDTree). Multiple trees correspond to the randomized KDTree
  32. forest as in @cite{silpa-anan08optimised},@cite{muja09fast}.
  33. To let the KD-tree index some data use ::vl_kdforest_build. Note that
  34. for efficiency KD-tree does not copy the data but retains a pointer to
  35. it. Therefore the data must exist (and not change) until the KD-tree
  36. is deleted. To delete the KD-tree object, use ::vl_kdforest_delete.
  37. To find the N nearest neighbors to a query point first instantiate
  38. a ::VlKDForestSearcher and then start search using a ::vl_kdforest_query
  39. with the searcher object as an argument. To set a maximum number of
  40. comparisons per query and calculate approximate nearest neighbors use
  41. ::vl_kdforest_set_max_num_comparisons.
  42. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  43. @section kdtree-tech Technical details
  44. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  45. ::VlKDForest implements the best-bin-first kd-tree of @cite{beis97shape}.
  46. <b>Construction.</b> Given a set of points @f$ x_1,\dots,x_n \in
  47. \mathbb{R}^d @f$, the algorithm recursively partitions the @e d
  48. dimensional Euclidean space @f$ \mathbb{R}^d @f$ into (hyper-)
  49. rectangles.
  50. Partitions are organized into a binary tree with the root
  51. corresponding to the whole space @f$ \mathbb{R}^d @f$. The algorithm
  52. refines each partition by dividing it into two halves by thresholding
  53. along a given dimension. Both the splitting dimension and the
  54. threshold are determined as a statistic of the data points contained
  55. in the partition. The splitting dimension is the one which has largest
  56. sample variance and the splitting threshold is either the sample mean
  57. or the median. Leaves are atomic partitions and they contain a list of
  58. zero or more data points (typically one).
  59. <b>Querying.</b> Querying amounts to finding the N data points closer
  60. to a given query point @f$ x_q \in \mathbb{R}^d @f$. This is done by
  61. branch-and-bound. A search state is an active partition (initially the
  62. root) and it is weighed by the lower bound on the distance of any
  63. point in the partition and the query point. Such a lower bound is
  64. trivial to compute because partitions are hyper-rectangles.
  65. <b>Querying usage.</b> As said before a user has to create an instance
  66. ::VlKDForestSearcher using ::vl_kdforest_new_searcher in order to be able
  67. to make queries. When a user wants to delete a KD-Tree all the searchers
  68. bound to the given KD-Forest are erased automatically. If a user wants to
  69. delete some of the searchers before the KD-Tree erase, he could do it
  70. using the vl_kdforest_delete_searcher method.
  71. **/
  72. #include "kdtree.h"
  73. #include "generic.h"
  74. #include "random.h"
  75. #include "mathop.h"
  76. #include <stdlib.h>
  77. #if defined(_OPENMP)
  78. #include <omp.h>
  79. #endif
  80. #define VL_HEAP_prefix vl_kdforest_search_heap
  81. #define VL_HEAP_type VlKDForestSearchState
  82. #define VL_HEAP_cmp(v,x,y) (v[x].distanceLowerBound - v[y].distanceLowerBound)
  83. #include "heap-def.h"
  84. #define VL_HEAP_prefix vl_kdtree_split_heap
  85. #define VL_HEAP_type VlKDTreeSplitDimension
  86. #define VL_HEAP_cmp(v,x,y) (v[x].variance - v[y].variance)
  87. #include "heap-def.h"
  88. #define VL_HEAP_prefix vl_kdforest_neighbor_heap
  89. #define VL_HEAP_type VlKDForestNeighbor
  90. #define VL_HEAP_cmp(v,x,y) (v[y].distance - v[x].distance)
  91. #include "heap-def.h"
  92. /** ------------------------------------------------------------------
  93. ** @internal
  94. ** @brief Allocate a new node from the tree pool
  95. **/
  96. static vl_uindex
  97. vl_kdtree_node_new (VlKDTree * tree, vl_uindex parentIndex)
  98. {
  99. VlKDTreeNode * node = NULL ;
  100. vl_uindex nodeIndex = tree->numUsedNodes ;
  101. tree -> numUsedNodes += 1 ;
  102. assert (tree->numUsedNodes <= tree->numAllocatedNodes) ;
  103. node = tree->nodes + nodeIndex ;
  104. node -> parent = parentIndex ;
  105. node -> lowerChild = 0 ;
  106. node -> upperChild = 0 ;
  107. node -> splitDimension = 0 ;
  108. node -> splitThreshold = 0 ;
  109. return nodeIndex ;
  110. }
  111. /** ------------------------------------------------------------------
  112. ** @internal
  113. ** @brief Compare KDTree index entries for sorting
  114. **/
  115. VL_INLINE int
  116. vl_kdtree_compare_index_entries (void const * a,
  117. void const * b)
  118. {
  119. double delta =
  120. ((VlKDTreeDataIndexEntry const*)a) -> value -
  121. ((VlKDTreeDataIndexEntry const*)b) -> value ;
  122. if (delta < 0) return -1 ;
  123. if (delta > 0) return +1 ;
  124. return 0 ;
  125. }
  126. /** ------------------------------------------------------------------
  127. ** @internal
  128. ** @brief Build KDTree recursively
  129. ** @param forest forest to which the tree belongs.
  130. ** @param tree tree being built.
  131. ** @param nodeIndex node to process.
  132. ** @param dataBegin begin of data for this node.
  133. ** @param dataEnd end of data for this node.
  134. ** @param depth depth of this node.
  135. **/
  136. static void
  137. vl_kdtree_build_recursively
  138. (VlKDForest * forest,
  139. VlKDTree * tree, vl_uindex nodeIndex,
  140. vl_uindex dataBegin, vl_uindex dataEnd,
  141. unsigned int depth)
  142. {
  143. vl_uindex d, i, medianIndex, splitIndex ;
  144. VlKDTreeNode * node = tree->nodes + nodeIndex ;
  145. VlKDTreeSplitDimension * splitDimension ;
  146. /* base case: there is only one data point */
  147. if (dataEnd - dataBegin <= 1) {
  148. if (tree->depth < depth) tree->depth = depth ;
  149. node->lowerChild = - ((int)dataBegin) - 1;
  150. node->upperChild = -((int)dataEnd) - 1;
  151. return ;
  152. }
  153. /* compute the dimension with largest variance > 0 */
  154. forest->splitHeapNumNodes = 0 ;
  155. for (d = 0 ; d < forest->dimension ; ++ d) {
  156. double mean = 0 ; /* unnormalized */
  157. double secondMoment = 0 ;
  158. double variance = 0 ;
  159. vl_size numSamples = VL_KDTREE_VARIANCE_EST_NUM_SAMPLES;
  160. vl_bool useAllData = VL_FALSE;
  161. if(dataEnd - dataBegin <= VL_KDTREE_VARIANCE_EST_NUM_SAMPLES) {
  162. useAllData = VL_TRUE;
  163. numSamples = dataEnd - dataBegin;
  164. }
  165. for (i = 0; i < numSamples ; ++ i) {
  166. vl_uint32 sampleIndex;
  167. vl_index di;
  168. double datum ;
  169. if(useAllData == VL_TRUE) {
  170. sampleIndex = (vl_uint32)i;
  171. } else {
  172. sampleIndex = (vl_rand_uint32(forest->rand) % VL_KDTREE_VARIANCE_EST_NUM_SAMPLES);
  173. }
  174. sampleIndex += dataBegin;
  175. di = tree->dataIndex[sampleIndex].index ;
  176. switch(forest->dataType) {
  177. case VL_TYPE_FLOAT: datum = ((float const*)forest->data)
  178. [di * forest->dimension + d] ;
  179. break ;
  180. case VL_TYPE_DOUBLE: datum = ((double const*)forest->data)
  181. [di * forest->dimension + d] ;
  182. break ;
  183. default:
  184. abort() ;
  185. }
  186. mean += datum ;
  187. secondMoment += datum * datum ;
  188. }
  189. mean /= numSamples ;
  190. secondMoment /= numSamples ;
  191. variance = secondMoment - mean * mean ;
  192. if (variance <= 0) continue ;
  193. /* keep splitHeapSize most varying dimensions */
  194. if (forest->splitHeapNumNodes < forest->splitHeapSize) {
  195. VlKDTreeSplitDimension * splitDimension
  196. = forest->splitHeapArray + forest->splitHeapNumNodes ;
  197. splitDimension->dimension = (unsigned int)d ;
  198. splitDimension->mean = mean ;
  199. splitDimension->variance = variance ;
  200. vl_kdtree_split_heap_push (forest->splitHeapArray, &forest->splitHeapNumNodes) ;
  201. } else {
  202. VlKDTreeSplitDimension * splitDimension = forest->splitHeapArray + 0 ;
  203. if (splitDimension->variance < variance) {
  204. splitDimension->dimension = (unsigned int)d ;
  205. splitDimension->mean = mean ;
  206. splitDimension->variance = variance ;
  207. vl_kdtree_split_heap_update (forest->splitHeapArray, forest->splitHeapNumNodes, 0) ;
  208. }
  209. }
  210. }
  211. /* additional base case: the maximum variance is equal to 0 (overlapping points) */
  212. if (forest->splitHeapNumNodes == 0) {
  213. node->lowerChild = -((int)dataBegin) - 1;
  214. node->upperChild = -((int)dataEnd) - 1;
  215. return ;
  216. }
  217. /* toss a dice to decide the splitting dimension (variance > 0) */
  218. splitDimension = forest->splitHeapArray
  219. + (vl_rand_uint32(forest->rand) % VL_MIN(forest->splitHeapSize, forest->splitHeapNumNodes)) ;
  220. node->splitDimension = splitDimension->dimension ;
  221. /* sort data along largest variance dimension */
  222. for (i = dataBegin ; i < dataEnd ; ++ i) {
  223. vl_index di = tree->dataIndex[i].index ;
  224. double datum ;
  225. switch (forest->dataType) {
  226. case VL_TYPE_FLOAT: datum = ((float const*)forest->data)
  227. [di * forest->dimension + splitDimension->dimension] ;
  228. break ;
  229. case VL_TYPE_DOUBLE: datum = ((double const*)forest->data)
  230. [di * forest->dimension + splitDimension->dimension] ;
  231. break ;
  232. default:
  233. abort() ;
  234. }
  235. tree->dataIndex [i] .value = datum ;
  236. }
  237. qsort (tree->dataIndex + dataBegin,
  238. dataEnd - dataBegin,
  239. sizeof (VlKDTreeDataIndexEntry),
  240. vl_kdtree_compare_index_entries) ;
  241. /* determine split threshold */
  242. switch (forest->thresholdingMethod) {
  243. case VL_KDTREE_MEAN :
  244. node->splitThreshold = splitDimension->mean ;
  245. for (splitIndex = dataBegin ;
  246. splitIndex < dataEnd && tree->dataIndex[splitIndex].value <= node->splitThreshold ;
  247. ++ splitIndex) ;
  248. splitIndex -= 1 ;
  249. /* If the mean does not provide a proper partition, fall back to
  250. * median. This usually happens if all points have the same
  251. * value and the zero variance test fails for numerical accuracy
  252. * reasons. In this case, also due to numerical accuracy, the
  253. * mean value can be smaller, equal, or larger than all
  254. * points. */
  255. if (dataBegin <= splitIndex && splitIndex + 1 < dataEnd) break ;
  256. case VL_KDTREE_MEDIAN :
  257. medianIndex = (dataBegin + dataEnd - 1) / 2 ;
  258. splitIndex = medianIndex ;
  259. node -> splitThreshold = tree->dataIndex[medianIndex].value ;
  260. break ;
  261. default:
  262. abort() ;
  263. }
  264. /* divide subparts */
  265. node->lowerChild = vl_kdtree_node_new (tree, nodeIndex) ;
  266. vl_kdtree_build_recursively (forest, tree, node->lowerChild, dataBegin, splitIndex + 1, depth + 1) ;
  267. node->upperChild = vl_kdtree_node_new (tree, nodeIndex) ;
  268. vl_kdtree_build_recursively (forest, tree, node->upperChild, splitIndex + 1, dataEnd, depth + 1) ;
  269. }
  270. /** ------------------------------------------------------------------
  271. ** @brief Create new KDForest object
  272. ** @param dataType type of data (::VL_TYPE_FLOAT or ::VL_TYPE_DOUBLE)
  273. ** @param dimension data dimensionality.
  274. ** @param numTrees number of trees in the forest.
  275. ** @param distance type of distance norm (::VlDistanceL1 or ::VlDistanceL2).
  276. ** @return new KDForest.
  277. **
  278. ** The data dimension @a dimension and the number of trees @a
  279. ** numTrees must not be smaller than one.
  280. **/
  281. VlKDForest *
  282. vl_kdforest_new (vl_type dataType,
  283. vl_size dimension, vl_size numTrees, VlVectorComparisonType distance)
  284. {
  285. VlKDForest * self = (VlKDForest*)vl_calloc (sizeof(VlKDForest), 1) ;
  286. assert(dataType == VL_TYPE_FLOAT || dataType == VL_TYPE_DOUBLE) ;
  287. assert(dimension >= 1) ;
  288. assert(numTrees >= 1) ;
  289. self -> rand = vl_get_rand () ;
  290. self -> dataType = dataType ;
  291. self -> numData = 0 ;
  292. self -> data = 0 ;
  293. self -> dimension = dimension ;
  294. self -> numTrees = numTrees ;
  295. self -> trees = 0 ;
  296. self -> thresholdingMethod = VL_KDTREE_MEDIAN ;
  297. self -> splitHeapSize = VL_MIN(numTrees, VL_KDTREE_SPLIT_HEAP_SIZE) ;
  298. self -> splitHeapNumNodes = 0 ;
  299. self -> distance = distance;
  300. self -> maxNumNodes = 0 ;
  301. self -> numSearchers = 0 ;
  302. self -> headSearcher = 0 ;
  303. switch (self->dataType) {
  304. case VL_TYPE_FLOAT:
  305. self -> distanceFunction = (void(*)(void))
  306. vl_get_vector_comparison_function_f (distance) ;
  307. break;
  308. case VL_TYPE_DOUBLE :
  309. self -> distanceFunction = (void(*)(void))
  310. vl_get_vector_comparison_function_d (distance) ;
  311. break ;
  312. default :
  313. abort() ;
  314. }
  315. return self ;
  316. }
  317. /** ------------------------------------------------------------------
  318. ** @brief Create a KDForest searcher object, used for processing queries
  319. ** @param kdforest a forest to which the queries should be pointing.
  320. ** @return KDForest searcher object.
  321. **
  322. ** A searcher is an object attached to the forest which must be created
  323. ** before running the queries. Each query has to be invoked with the
  324. ** searcher as its argument.
  325. **
  326. ** When using a multi-threaded approach a user should at first instantiate
  327. ** a correct number of searchers - each used in one thread.
  328. ** Then in each thread a query to the given searcher could be run.
  329. **
  330. **/
  331. VlKDForestSearcher *
  332. vl_kdforest_new_searcher (VlKDForest * kdforest)
  333. {
  334. VlKDForestSearcher * self = (VlKDForestSearcher*)vl_calloc(sizeof(VlKDForestSearcher), 1);
  335. if(kdforest->numSearchers == 0) {
  336. kdforest->headSearcher = self;
  337. self->previous = NULL;
  338. self->next = NULL;
  339. } else {
  340. VlKDForestSearcher * lastSearcher = kdforest->headSearcher;
  341. while (1) {
  342. if(lastSearcher->next) {
  343. lastSearcher = lastSearcher->next;
  344. } else {
  345. lastSearcher->next = self;
  346. self->previous = lastSearcher;
  347. self->next = NULL;
  348. break;
  349. }
  350. }
  351. }
  352. kdforest->numSearchers++;
  353. self->forest = kdforest;
  354. self->searchHeapArray = (VlKDForestSearchState*)vl_malloc (sizeof(VlKDForestSearchState) * kdforest->maxNumNodes) ;
  355. self->searchIdBook = (vl_uindex*)vl_calloc (sizeof(vl_uindex), kdforest->numData) ;
  356. return self ;
  357. }
  358. /** ------------------------------------------------------------------
  359. ** @brief Delete object
  360. ** @param self object.
  361. **/
  362. void
  363. vl_kdforestsearcher_delete (VlKDForestSearcher * self)
  364. {
  365. if (self->previous && self->next) {
  366. self->previous->next = self->next;
  367. self->next->previous = self->previous;
  368. } else if (self->previous && !self->next) {
  369. self->previous->next = NULL;
  370. } else if (!self->previous && self->next) {
  371. self->next->previous = NULL;
  372. self->forest->headSearcher = self->next;
  373. } else {
  374. self->forest->headSearcher = NULL;
  375. }
  376. self->forest->numSearchers -- ;
  377. vl_free(self->searchHeapArray) ;
  378. vl_free(self->searchIdBook) ;
  379. vl_free(self) ;
  380. }
  381. VlKDForestSearcher *
  382. vl_kdforest_get_searcher (VlKDForest const * self, vl_uindex pos)
  383. {
  384. VlKDForestSearcher * lastSearcher = self->headSearcher ;
  385. vl_uindex i ;
  386. for(i = 0; (i < pos) & (lastSearcher != NULL) ; ++i) {
  387. lastSearcher = lastSearcher->next ;
  388. }
  389. return lastSearcher ;
  390. }
  391. /** ------------------------------------------------------------------
  392. ** @brief Delete KDForest object
  393. ** @param self KDForest object to delete
  394. ** @sa ::vl_kdforest_new
  395. **/
  396. void
  397. vl_kdforest_delete (VlKDForest * self)
  398. {
  399. vl_uindex ti ;
  400. VlKDForestSearcher * searcher ;
  401. while ((searcher = vl_kdforest_get_searcher(self, 0))) {
  402. vl_kdforestsearcher_delete(searcher) ;
  403. }
  404. if (self->trees) {
  405. for (ti = 0 ; ti < self->numTrees ; ++ ti) {
  406. if (self->trees[ti]) {
  407. if (self->trees[ti]->nodes) vl_free (self->trees[ti]->nodes) ;
  408. if (self->trees[ti]->dataIndex) vl_free (self->trees[ti]->dataIndex) ;
  409. vl_free (self->trees[ti]) ;
  410. }
  411. }
  412. vl_free (self->trees) ;
  413. }
  414. vl_free (self) ;
  415. }
  416. /** ------------------------------------------------------------------
  417. ** @internal @brief Compute tree bounds recursively
  418. ** @param tree KDTree object instance.
  419. ** @param nodeIndex node index to start from.
  420. ** @param searchBounds 2 x numDimension array of bounds.
  421. **/
  422. static void
  423. vl_kdtree_calc_bounds_recursively (VlKDTree * tree,
  424. vl_uindex nodeIndex, double * searchBounds)
  425. {
  426. VlKDTreeNode * node = tree->nodes + nodeIndex ;
  427. vl_uindex i = node->splitDimension ;
  428. double t = node->splitThreshold ;
  429. node->lowerBound = searchBounds [2 * i + 0] ;
  430. node->upperBound = searchBounds [2 * i + 1] ;
  431. //VL_PRINT("%f %f\n",node->lowerBound,node->upperBound);
  432. if (node->lowerChild > 0) {
  433. searchBounds [2 * i + 1] = t ;
  434. vl_kdtree_calc_bounds_recursively (tree, node->lowerChild, searchBounds) ;
  435. searchBounds [2 * i + 1] = node->upperBound ;
  436. }
  437. if (node->upperChild > 0) {
  438. searchBounds [2 * i + 0] = t ;
  439. vl_kdtree_calc_bounds_recursively (tree, node->upperChild, searchBounds) ;
  440. searchBounds [2 * i + 0] = node->lowerBound ;
  441. }
  442. }
  443. /** ------------------------------------------------------------------
  444. ** @brief Build KDTree from data
  445. ** @param self KDTree object
  446. ** @param numData number of data points.
  447. ** @param data pointer to the data.
  448. **
  449. ** The function builds the KDTree by processing the data @a data. For
  450. ** efficiency, KDTree does not make a copy the data, but retains a
  451. ** pointer to it. Therefore the data buffer must be valid and
  452. ** unchanged for the lifespan of the object.
  453. **
  454. ** The number of data points @c numData must not be smaller than one.
  455. **/
  456. void
  457. vl_kdforest_build (VlKDForest * self, vl_size numData, void const * data)
  458. {
  459. vl_uindex di, ti ;
  460. vl_size maxNumNodes ;
  461. double * searchBounds;
  462. assert(data) ;
  463. assert(numData >= 1) ;
  464. /* need to check: if alredy built, clean first */
  465. self->data = data ;
  466. self->numData = numData ;
  467. self->trees = (VlKDTree**)vl_malloc (sizeof(VlKDTree*) * self->numTrees) ;
  468. maxNumNodes = 0 ;
  469. for (ti = 0 ; ti < self->numTrees ; ++ ti) {
  470. self->trees[ti] = (VlKDTree*)vl_malloc (sizeof(VlKDTree)) ;
  471. self->trees[ti]->dataIndex = (VlKDTreeDataIndexEntry*)vl_malloc (sizeof(VlKDTreeDataIndexEntry) * self->numData) ;
  472. for (di = 0 ; di < self->numData ; ++ di) {
  473. self->trees[ti]->dataIndex[di].index = di ;
  474. }
  475. self->trees[ti]->numUsedNodes = 0 ;
  476. /* num. nodes of a complete binary tree with numData leaves */
  477. self->trees[ti]->numAllocatedNodes = 2 * self->numData - 1 ;
  478. self->trees[ti]->nodes = (VlKDTreeNode*)vl_malloc (sizeof(VlKDTreeNode) * self->trees[ti]->numAllocatedNodes) ;
  479. self->trees[ti]->depth = 0 ;
  480. vl_kdtree_build_recursively (self, self->trees[ti],
  481. vl_kdtree_node_new(self->trees[ti], 0), 0,
  482. self->numData, 0) ;
  483. maxNumNodes += self->trees[ti]->numUsedNodes ;
  484. }
  485. searchBounds = (double*)vl_malloc(sizeof(double) * 2 * self->dimension);
  486. for (ti = 0 ; ti < self->numTrees ; ++ ti) {
  487. double * iter = searchBounds ;
  488. double * end = iter + 2 * self->dimension ;
  489. while (iter < end) {
  490. *iter++ = - VL_INFINITY_F ;
  491. *iter++ = + VL_INFINITY_F ;
  492. }
  493. vl_kdtree_calc_bounds_recursively (self->trees[ti], 0, searchBounds) ;
  494. }
  495. vl_free(searchBounds);
  496. self -> maxNumNodes = maxNumNodes;
  497. }
  498. /** ------------------------------------------------------------------
  499. ** @internal @brief
  500. **/
  501. vl_uindex
  502. vl_kdforest_query_recursively (VlKDForestSearcher * searcher,
  503. VlKDTree * tree,
  504. vl_uindex nodeIndex,
  505. VlKDForestNeighbor * neighbors,
  506. vl_size numNeighbors,
  507. vl_size * numAddedNeighbors,
  508. double dist,
  509. void const * query)
  510. {
  511. VlKDTreeNode const * node = tree->nodes + nodeIndex ;
  512. vl_uindex i = node->splitDimension ;
  513. vl_index nextChild, saveChild ;
  514. double delta, saveDist ;
  515. double x ;
  516. double x1 = node->lowerBound ;
  517. double x2 = node->splitThreshold ;
  518. double x3 = node->upperBound ;
  519. VlKDForestSearchState * searchState ;
  520. searcher->searchNumRecursions ++ ;
  521. switch (searcher->forest->dataType) {
  522. case VL_TYPE_FLOAT :
  523. x = ((float const*) query)[i] ;
  524. break ;
  525. case VL_TYPE_DOUBLE :
  526. x = ((double const*) query)[i] ;
  527. break ;
  528. default :
  529. abort() ;
  530. }
  531. /* base case: this is a leaf node */
  532. if (node->lowerChild < 0) {
  533. vl_index begin = - node->lowerChild - 1 ;
  534. vl_index end = - node->upperChild - 1 ;
  535. vl_index iter ;
  536. for (iter = begin ;
  537. iter < end &&
  538. (searcher->forest->searchMaxNumComparisons == 0 ||
  539. searcher->searchNumComparisons < searcher->forest->searchMaxNumComparisons) ;
  540. ++ iter) {
  541. vl_index di = tree->dataIndex [iter].index ;
  542. /* multiple KDTrees share the database points and we must avoid
  543. * adding the same point twice */
  544. if (searcher->searchIdBook[di] == searcher->searchId) continue ;
  545. searcher->searchIdBook[di] = searcher->searchId ;
  546. /* compare the query to this point */
  547. switch (searcher->forest->dataType) {
  548. case VL_TYPE_FLOAT:
  549. dist = ((VlFloatVectorComparisonFunction)searcher->forest->distanceFunction)
  550. (searcher->forest->dimension,
  551. ((float const *)query),
  552. ((float const*)searcher->forest->data) + di * searcher->forest->dimension) ;
  553. break ;
  554. case VL_TYPE_DOUBLE:
  555. dist = ((VlDoubleVectorComparisonFunction)searcher->forest->distanceFunction)
  556. (searcher->forest->dimension,
  557. ((double const *)query),
  558. ((double const*)searcher->forest->data) + di * searcher->forest->dimension) ;
  559. break ;
  560. default:
  561. abort() ;
  562. }
  563. searcher->searchNumComparisons += 1 ;
  564. /* see if it should be added to the result set */
  565. if (*numAddedNeighbors < numNeighbors) {
  566. VlKDForestNeighbor * newNeighbor = neighbors + *numAddedNeighbors ;
  567. newNeighbor->index = di ;
  568. newNeighbor->distance = dist ;
  569. vl_kdforest_neighbor_heap_push (neighbors, numAddedNeighbors) ;
  570. } else {
  571. VlKDForestNeighbor * largestNeighbor = neighbors + 0 ;
  572. if (largestNeighbor->distance > dist) {
  573. largestNeighbor->index = di ;
  574. largestNeighbor->distance = dist ;
  575. vl_kdforest_neighbor_heap_update (neighbors, *numAddedNeighbors, 0) ;
  576. }
  577. }
  578. } /* next data point */
  579. return nodeIndex ;
  580. }
  581. #if 0
  582. assert (x1 <= x2 && x2 <= x3) ;
  583. assert (node->lowerChild >= 0) ;
  584. assert (node->upperChild >= 0) ;
  585. #endif
  586. /*
  587. * x1 x2 x3
  588. * x (---|---]
  589. * (--x|---]
  590. * (---|x--]
  591. * (---|---] x
  592. */
  593. delta = x - x2 ;
  594. saveDist = dist + delta*delta ;
  595. if (x <= x2) {
  596. nextChild = node->lowerChild ;
  597. saveChild = node->upperChild ;
  598. if (x <= x1) {
  599. delta = x - x1 ;
  600. saveDist -= delta*delta ;
  601. }
  602. } else {
  603. nextChild = node->upperChild ;
  604. saveChild = node->lowerChild ;
  605. if (x > x3) {
  606. delta = x - x3 ;
  607. saveDist -= delta*delta ;
  608. }
  609. }
  610. if (*numAddedNeighbors < numNeighbors || neighbors[0].distance > saveDist) {
  611. searchState = searcher->searchHeapArray + searcher->searchHeapNumNodes ;
  612. searchState->tree = tree ;
  613. searchState->nodeIndex = saveChild ;
  614. searchState->distanceLowerBound = saveDist ;
  615. vl_kdforest_search_heap_push (searcher->searchHeapArray ,
  616. &searcher->searchHeapNumNodes) ;
  617. }
  618. return vl_kdforest_query_recursively (searcher,
  619. tree,
  620. nextChild,
  621. neighbors,
  622. numNeighbors,
  623. numAddedNeighbors,
  624. dist,
  625. query) ;
  626. }
  627. /** ------------------------------------------------------------------
  628. ** @brief Query the forest
  629. ** @param self object.
  630. ** @param neighbors list of nearest neighbors found (output).
  631. ** @param numNeighbors number of nearest neighbors to find.
  632. ** @param query query point.
  633. ** @return number of tree leaves visited.
  634. **
  635. ** A neighbor is represented by an instance of the structure
  636. ** ::VlKDForestNeighbor. Each entry contains the index of the
  637. ** neighbor (this is an index into the KDTree data) and its distance
  638. ** to the query point. Neighbors are sorted by increasing distance.
  639. **/
  640. vl_size
  641. vl_kdforest_query (VlKDForest * self,
  642. VlKDForestNeighbor * neighbors,
  643. vl_size numNeighbors,
  644. void const * query)
  645. {
  646. VlKDForestSearcher * searcher = vl_kdforest_get_searcher(self, 0) ;
  647. if (searcher == NULL) {
  648. searcher = vl_kdforest_new_searcher(self) ;
  649. }
  650. return vl_kdforestsearcher_query(searcher,
  651. neighbors,
  652. numNeighbors,
  653. query) ;
  654. }
  655. /** ------------------------------------------------------------------
  656. ** @brief Query the forest
  657. ** @param self object.
  658. ** @param neighbors list of nearest neighbors found (output).
  659. ** @param numNeighbors number of nearest neighbors to find.
  660. ** @param query query point.
  661. ** @return number of tree leaves visited.
  662. **
  663. ** A neighbor is represented by an instance of the structure
  664. ** ::VlKDForestNeighbor. Each entry contains the index of the
  665. ** neighbor (this is an index into the KDTree data) and its distance
  666. ** to the query point. Neighbors are sorted by increasing distance.
  667. **/
  668. vl_size
  669. vl_kdforestsearcher_query (VlKDForestSearcher * self,
  670. VlKDForestNeighbor * neighbors,
  671. vl_size numNeighbors,
  672. void const * query)
  673. {
  674. vl_uindex i, ti ;
  675. vl_bool exactSearch = self->forest->searchMaxNumComparisons == 0 ;
  676. VlKDForestSearchState * searchState ;
  677. vl_size numAddedNeighbors = 0 ;
  678. assert (neighbors) ;
  679. assert (numNeighbors > 0) ;
  680. assert (query) ;
  681. /* this number is used to differentiate a query from the next */
  682. self -> searchId += 1 ;
  683. self -> searchNumRecursions = 0 ;
  684. self->searchNumComparisons = 0 ;
  685. self->searchNumSimplifications = 0 ;
  686. /* put the root node into the search heap */
  687. self->searchHeapNumNodes = 0 ;
  688. for (ti = 0 ; ti < self->forest->numTrees ; ++ ti) {
  689. searchState = self->searchHeapArray + self->searchHeapNumNodes ;
  690. searchState -> tree = self->forest->trees[ti] ;
  691. searchState -> nodeIndex = 0 ;
  692. searchState -> distanceLowerBound = 0 ;
  693. vl_kdforest_search_heap_push (self->searchHeapArray, &self->searchHeapNumNodes) ;
  694. }
  695. /* branch and bound */
  696. while (exactSearch || self->searchNumComparisons < self->forest->searchMaxNumComparisons)
  697. {
  698. /* pop the next optimal search node */
  699. VlKDForestSearchState * searchState ;
  700. /* break if search space completed */
  701. if (self->searchHeapNumNodes == 0) {
  702. break ;
  703. }
  704. searchState = self->searchHeapArray +
  705. vl_kdforest_search_heap_pop (self->searchHeapArray, &self->searchHeapNumNodes) ;
  706. /* break if no better solution may exist */
  707. if (numAddedNeighbors == numNeighbors &&
  708. neighbors[0].distance < searchState->distanceLowerBound) {
  709. self->searchNumSimplifications ++ ;
  710. break ;
  711. }
  712. vl_kdforest_query_recursively (self,
  713. searchState->tree,
  714. searchState->nodeIndex,
  715. neighbors,
  716. numNeighbors,
  717. &numAddedNeighbors,
  718. searchState->distanceLowerBound,
  719. query) ;
  720. }
  721. /* sort neighbors by increasing distance */
  722. for (i = numAddedNeighbors ; i < numNeighbors ; ++ i) {
  723. neighbors[i].index = -1 ;
  724. neighbors[i].distance = VL_NAN_F ;
  725. }
  726. while (numAddedNeighbors) {
  727. vl_kdforest_neighbor_heap_pop (neighbors, &numAddedNeighbors) ;
  728. }
  729. return self->searchNumComparisons ;
  730. }
  731. /** ------------------------------------------------------------------
  732. ** @brief Run multiple queries
  733. ** @param self object.
  734. ** @param indexes assignments of points.
  735. ** @param numNeighbors number of nearest neighbors to be found for each data point
  736. ** @param numQueries number of query points.
  737. ** @param distances distances of query points.
  738. ** @param queries lisf of vectors to use as queries.
  739. **
  740. ** @a indexes and @a distances are @a numNeighbors by @a numQueries
  741. ** matrices containing the indexes and distances of the nearest neighbours
  742. ** for each of the @a numQueries queries @a queries.
  743. **
  744. ** This function is similar to ::vl_kdforest_query. The main
  745. ** difference is that the function can use multiple cores to query
  746. ** large amounts of data.
  747. **
  748. ** @sa ::vl_kdforest_query.
  749. **/
  750. vl_size
  751. vl_kdforest_query_with_array (VlKDForest * self,
  752. vl_uint32 * indexes,
  753. vl_size numNeighbors,
  754. vl_size numQueries,
  755. void * distances,
  756. void const * queries)
  757. {
  758. vl_size numComparisons = 0;
  759. vl_type dataType = vl_kdforest_get_data_type(self) ;
  760. vl_size dimension = vl_kdforest_get_data_dimension(self) ;
  761. #ifdef _OPENMP
  762. #pragma omp parallel default(shared) num_threads(vl_get_max_threads())
  763. #endif
  764. {
  765. vl_index qi ;
  766. vl_size thisNumComparisons = 0 ;
  767. VlKDForestSearcher * searcher ;
  768. VlKDForestNeighbor * neighbors ;
  769. #ifdef _OPENMP
  770. #pragma omp critical
  771. #endif
  772. {
  773. searcher = vl_kdforest_new_searcher(self) ;
  774. neighbors = (VlKDForestNeighbor*)vl_calloc (sizeof(VlKDForestNeighbor), numNeighbors) ;
  775. }
  776. #ifdef _OPENMP
  777. #pragma omp for
  778. #endif
  779. for(qi = 0 ; qi < (signed)numQueries; ++ qi) {
  780. switch (dataType) {
  781. case VL_TYPE_FLOAT: {
  782. vl_size ni;
  783. thisNumComparisons += vl_kdforestsearcher_query (searcher, neighbors, numNeighbors,
  784. (float const *) (queries) + qi * dimension) ;
  785. for (ni = 0 ; ni < numNeighbors ; ++ni) {
  786. indexes [qi*numNeighbors + ni] = (vl_uint32) neighbors[ni].index ;
  787. if (distances){
  788. *((float*)distances + qi*numNeighbors + ni) = neighbors[ni].distance ;
  789. }
  790. }
  791. break ;
  792. }
  793. case VL_TYPE_DOUBLE: {
  794. vl_size ni;
  795. thisNumComparisons += vl_kdforestsearcher_query (searcher, neighbors, numNeighbors,
  796. (double const *) (queries) + qi * dimension) ;
  797. for (ni = 0 ; ni < numNeighbors ; ++ni) {
  798. indexes [qi*numNeighbors + ni] = (vl_uint32) neighbors[ni].index ;
  799. if (distances){
  800. *((double*)distances + qi*numNeighbors + ni) = neighbors[ni].distance ;
  801. }
  802. }
  803. break ;
  804. }
  805. default:
  806. abort() ;
  807. }
  808. }
  809. #ifdef _OPENMP
  810. #pragma omp critical
  811. #endif
  812. {
  813. numComparisons += thisNumComparisons ;
  814. vl_kdforestsearcher_delete (searcher) ;
  815. vl_free (neighbors) ;
  816. }
  817. }
  818. return numComparisons ;
  819. }
  820. /** ------------------------------------------------------------------
  821. ** @brief Get the number of nodes of a given tree
  822. ** @param self KDForest object.
  823. ** @param treeIndex index of the tree.
  824. ** @return number of trees.
  825. **/
  826. vl_size
  827. vl_kdforest_get_num_nodes_of_tree (VlKDForest const * self, vl_uindex treeIndex)
  828. {
  829. assert (treeIndex < self->numTrees) ;
  830. return self->trees[treeIndex]->numUsedNodes ;
  831. }
  832. /** ------------------------------------------------------------------
  833. ** @brief Get the detph of a given tree
  834. ** @param self KDForest object.
  835. ** @param treeIndex index of the tree.
  836. ** @return number of trees.
  837. **/
  838. vl_size
  839. vl_kdforest_get_depth_of_tree (VlKDForest const * self, vl_uindex treeIndex)
  840. {
  841. assert (treeIndex < self->numTrees) ;
  842. return self->trees[treeIndex]->depth ;
  843. }
  844. /** ------------------------------------------------------------------
  845. ** @brief Get the number of trees in the forest
  846. **
  847. ** @param self KDForest object.
  848. ** @return number of trees.
  849. **/
  850. vl_size
  851. vl_kdforest_get_num_trees (VlKDForest const * self)
  852. {
  853. return self->numTrees ;
  854. }
  855. /** ------------------------------------------------------------------
  856. ** @brief Set the maximum number of comparisons for a search
  857. **
  858. ** @param self KDForest object.
  859. ** @param n maximum number of leaves.
  860. **
  861. ** This function sets the maximum number of comparisons for a
  862. ** nearest neighbor search. Setting it to 0 means unbounded comparisons.
  863. **
  864. ** @sa ::vl_kdforest_query, ::vl_kdforest_get_max_num_comparisons.
  865. **/
  866. void
  867. vl_kdforest_set_max_num_comparisons (VlKDForest * self, vl_size n)
  868. {
  869. self->searchMaxNumComparisons = n ;
  870. }
  871. /** ------------------------------------------------------------------
  872. ** @brief Get the maximum number of comparisons for a search
  873. **
  874. ** @param self KDForest object.
  875. ** @return maximum number of leaves.
  876. **
  877. ** @sa ::vl_kdforest_set_max_num_comparisons.
  878. **/
  879. vl_size
  880. vl_kdforest_get_max_num_comparisons (VlKDForest * self)
  881. {
  882. return self->searchMaxNumComparisons ;
  883. }
  884. /** ------------------------------------------------------------------
  885. ** @brief Set the thresholding method
  886. ** @param self KDForest object.
  887. ** @param method one of ::VlKDTreeThresholdingMethod.
  888. **
  889. ** @sa ::vl_kdforest_get_thresholding_method
  890. **/
  891. void
  892. vl_kdforest_set_thresholding_method (VlKDForest * self, VlKDTreeThresholdingMethod method)
  893. {
  894. assert(method == VL_KDTREE_MEDIAN || method == VL_KDTREE_MEAN) ;
  895. self->thresholdingMethod = method ;
  896. }
  897. /** ------------------------------------------------------------------
  898. ** @brief Get the thresholding method
  899. **
  900. ** @param self KDForest object.
  901. ** @return thresholding method.
  902. **
  903. ** @sa ::vl_kdforest_set_thresholding_method
  904. **/
  905. VlKDTreeThresholdingMethod
  906. vl_kdforest_get_thresholding_method (VlKDForest const * self)
  907. {
  908. return self->thresholdingMethod ;
  909. }
  910. /** ------------------------------------------------------------------
  911. ** @brief Get the dimension of the data
  912. ** @param self KDForest object.
  913. ** @return dimension of the data.
  914. **/
  915. vl_size
  916. vl_kdforest_get_data_dimension (VlKDForest const * self)
  917. {
  918. return self->dimension ;
  919. }
  920. /** ------------------------------------------------------------------
  921. ** @brief Get the data type
  922. ** @param self KDForest object.
  923. ** @return data type (one of ::VL_TYPE_FLOAT, ::VL_TYPE_DOUBLE).
  924. **/
  925. vl_type
  926. vl_kdforest_get_data_type (VlKDForest const * self)
  927. {
  928. return self->dataType ;
  929. }
  930. /** ------------------------------------------------------------------
  931. ** @brief Get the forest linked to the searcher
  932. ** @param self object.
  933. ** @return correspoinding KD-Forest.
  934. **/
  935. VlKDForest *
  936. vl_kdforestsearcher_get_forest (VlKDForestSearcher const * self)
  937. {
  938. return self->forest;
  939. }