Debian Codegraph @

src/thirdparty/VLFeat/kdtree.c

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