File size: 21,709 Bytes
d4035c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
/** @file   kdtree.c
 ** @brief  KD-tree - Definition
 ** @author Andrea Vedaldi
 **/

/* AUTORIGHTS
 Copyright (C) 2007-09 Andrea Vedaldi and Brian Fulkerson

 This file is part of VLFeat, available in the terms of the GNU
 General Public License version 2.
 */

#include "kdtree.h"
#include "generic.h"
#include "random.h"
#include "mathop.h"

#include <stdlib.h>

/** @file kdtree.h
 **
 ** ::VlKDTree implements a KD-tree object data structure useful to
 ** index moderately dimensional vector spaces. It can be used to
 ** quickly match two groups of feature descriptors.
 **
 ** - @ref kdtree-overview
 ** - @ref kdtree-tech
 **
 ** @section kdtree-overview Overview
 **
 ** To create a ::VlKDForest object use ::vl_kdforest_new specifying
 ** the dimensionality of the data and the number of trees in the
 ** forest.  With one tree only, the algorithm is analogous to [1]
 ** (best-bin KDTree). Multiple trees correspond to the randomized
 ** KDTree forest as in [2,3].
 **
 ** To let the KD-tree index some data use ::vl_kdforest_build. Note
 ** that for efficiency KD-tree does not copy the data but retains a
 ** pointer to it. Therefore the data must exist (and not change)
 ** until the KD-tree is deleted. To delete the KD-tree object, use
 ** ::vl_kdforest_delete.
 **
 ** To find the N nearest neighbors to a query point use
 ** ::vl_kdforest_query. To set a maximum number of comparisons per
 ** query and calculate approximate nearest neighbors use
 ** ::vl_kdforest_set_max_num_comparisons.
 **
 ** @section kdtree-tech Technical details
 ** @sa @ref kdtree-references
 **
 ** KDTree implements the best-bin-first kd-tree of [1]. Given a set
 ** of points @f$ x_1,\dots,x_n \in \mathbb{R}^d @f$, the algorithm
 ** recursively partitions the @e d dimensional Euclidean space @f$
 ** \mathbb{R}^d @f$ into (hyper-) rectangles.
 **
 ** Partitions are organized into a binary tree with the root
 ** corresponding to the whole space @f$ \mathbb{R}^d @f$. The
 ** algorithm refines each partition by dividing it into two halves by
 ** thresholding along a given dimension. Both the splitting dimension
 ** and the threshold are determined as a statistic of the data points
 ** contained in the partition. The splitting dimension is the one
 ** which has largest sample variance and the splitting threshold is
 ** either the sample mean or the median. Leaves are atomic partitions
 ** and they contain a list of zero or more data points (typically
 ** one).
 **
 ** Querying amounts to finding the N data points closer to a given
 ** query point @f$ x_q \in \mathbb{R}^d @f$. This is done by
 ** branch-and-bound. A search state is an active partition (initially
 ** the root) and it is weighed by the lower bound on the distance of
 ** any point in the partition and the query point. Such a lower bound
 ** is trivial to compute because partitions are hyper-rectangles.
 **
 ** @section kdtree-references References
 **
 ** [1] J. S. Beis and D. G. Lowe. Shape indexing using approximate
 ** nearest-neighbour search in high-dimensional spaces. In
 ** Proc. CVPR, 1997.
 **
 ** [2] C. Silpa-Anan and R. Hartley. Optimised KD-trees for fast
 ** image descriptor matching. In Proc. CVPR, 2008.
 **
 ** [3] M. Muja and D. G. Lowe. Fast approximate nearest neighbors
 ** with automatic algorithmic configuration. In Proc. VISAPP, 2009.
 **/

#define NAME vl_kdforest_search_heap
#define T VlKDForestSearchState
#define CMP(x,y) (x->distanceLowerBound - y->distanceLowerBound)
#include "heap-t.h"
#undef CMP
#undef T
#undef NAME

#define NAME vl_kdtree_split_heap
#define T VlKDTreeSplitDimension
#define CMP(x,y) (x->variance - y->variance)
#include "heap-t.h"
#undef CMP
#undef T
#undef NAME

#define NAME vl_kdforest_neighbor_heap
#define T VlKDForestNeighbor
#define CMP(x,y) (y->distance - x->distance)
#include "heap-t.h"
#undef CMP
#undef T
#undef NAME

/** ------------------------------------------------------------------
 ** @internal
 ** @brief Allocate a new node from the tree pool
 **
 **/

int unsigned
vl_kdtree_node_new (VlKDTree * tree, int unsigned parentIndex)
{
  VlKDTreeNode * node = NULL ;
  int unsigned nodeIndex = tree->numUsedNodes ;
  tree -> numUsedNodes += 1 ;

  assert (tree->numUsedNodes <= tree->numAllocatedNodes) ;

  node = tree->nodes + nodeIndex ;
  node -> parent = parentIndex ;
  node -> lowerChild = 0 ;
  node -> upperChild = 0 ;
  node -> splitDimension = 0 ;
  node -> splitThreshold = 0 ;
  return nodeIndex ;
}

/** ------------------------------------------------------------------
 ** @internal
 ** @brief Compare KDTree index entries for sorting
 **/

static int
vl_kdtree_compare_index_entries (void const * a,
                                 void const * b)
{
  float delta =
   ((VlKDTreeDataIndexEntry const*)a) -> value -
   ((VlKDTreeDataIndexEntry const*)b) -> value ;
  if (delta < 0) return -1 ;
  if (delta > 0) return +1 ;
  return 0 ;
}

/** ------------------------------------------------------------------
 ** @internal
 ** @brief Build KDTree recursively
 ** @param tree KDTree object.
 ** @param nodeIndex node to process.
 ** @param dataBegin begin of data for this node.
 ** @param dataEnd end of data for this node.
 ** @param depth depth of this node.
 **/

static void
vl_kdtree_build_recursively
(VlKDForest * forest,
 VlKDTree * tree, unsigned int nodeIndex,
 unsigned int dataBegin, unsigned int dataEnd,
 unsigned int depth)
{
  int d, i, medianIndex, splitIndex ;
  VlKDTreeNode * node = tree->nodes + nodeIndex ;
  VlKDTreeSplitDimension * splitDimension ;

  /* base case: there is only one data point */
  if (dataEnd - dataBegin <= 1) {
    if (tree->depth < depth) tree->depth = depth ;
    node->lowerChild = - dataBegin - 1;
    node->upperChild = - dataEnd - 1 ;
    return ;
  }

  /* compute the dimension with largest variance */
  forest->splitHeapNumNodes = 0 ;
  for (d = 0 ; d < forest->numDimensions ; ++ d) {
    float mean = 0 ; /* unnormalized */
    float secondMoment = 0 ;
    float variance = 0 ;
    for (i = dataBegin ; i < dataEnd ; ++ i) {
      int di = tree -> dataIndex [i] .index ;
      float const datum = forest->data [di * forest->numDimensions + d] ;
      mean += datum ;
      secondMoment += datum * datum ;
    }
    mean /= (dataEnd - dataBegin) ;
    secondMoment /= (dataEnd - dataBegin) ;
    variance = secondMoment - mean * mean ;

    /* keep splitHeapSize most varying dimensions */
    if (forest->splitHeapNumNodes < forest->splitHeapSize) {
      VlKDTreeSplitDimension * splitDimension
        = forest->splitHeapArray + forest->splitHeapNumNodes ;
      splitDimension->dimension = d ;
      splitDimension->mean = mean ;
      splitDimension->variance = variance ;
      vl_kdtree_split_heap_push (forest->splitHeapArray, &forest->splitHeapNumNodes) ;
    } else {
      VlKDTreeSplitDimension * splitDimension = forest->splitHeapArray + 0 ;
      if (splitDimension->variance < variance) {
        splitDimension->dimension = d ;
        splitDimension->mean = mean ;
        splitDimension->variance = variance ;
        vl_kdtree_split_heap_update (forest->splitHeapArray, forest->splitHeapNumNodes, 0) ;
      }
    }
  }

  /* toss a dice to decide the splitting dimension */
  splitDimension = forest->splitHeapArray
  + (vl_rand_uint32() % VL_MIN(forest->splitHeapSize, forest->splitHeapNumNodes)) ;

  /* additional base case: variance is equal to 0 (overlapping points) */
  if (splitDimension->variance == 0) {
    node->lowerChild = - dataBegin - 1 ;
    node->upperChild = - dataEnd - 1 ;
    return ;
  }
  node->splitDimension = splitDimension->dimension ;

  /* sort data along largest variance dimension */
  for (i = dataBegin ; i < dataEnd ; ++ i) {
    int di = tree->dataIndex [i] .index ;
    float datum = forest->data [di * forest->numDimensions + splitDimension->dimension] ;
    tree->dataIndex [i] .value = datum ;
  }
  qsort (tree->dataIndex + dataBegin,
         dataEnd - dataBegin,
         sizeof (VlKDTreeDataIndexEntry),
         vl_kdtree_compare_index_entries) ;

  /* determine split threshold */
  switch (forest->thresholdingMethod) {
    case VL_KDTREE_MEAN :
      node->splitThreshold = splitDimension->mean ;
      for (splitIndex = dataBegin ;
           splitIndex < dataEnd && tree->dataIndex[splitIndex].value <= node->splitThreshold ;
           ++ splitIndex) ;
      splitIndex -= 1 ;
      /* If the mean does not provide a proper partition, fall back to
       * median. This usually happens if all points have the same
       * value and the zero variance test fails for numerical accuracy
       * reasons. In this case, also due to numerical accuracy, the
       * mean value can be smaller, equal, or larger than all
       * points. */
      if (dataBegin <= splitIndex && splitIndex + 1 < dataEnd) break ;

    case VL_KDTREE_MEDIAN :
      medianIndex = (dataBegin + dataEnd - 1) / 2 ;
      splitIndex = medianIndex ;
      node -> splitThreshold = tree->dataIndex[medianIndex].value ;
      break ;

    default:
      assert(0) ;
  }

  /* divide subparts */
  node->lowerChild = vl_kdtree_node_new (tree, nodeIndex) ;
  vl_kdtree_build_recursively (forest, tree, node->lowerChild, dataBegin, splitIndex + 1, depth + 1) ;

  node->upperChild = vl_kdtree_node_new (tree, nodeIndex) ;
  vl_kdtree_build_recursively (forest, tree, node->upperChild, splitIndex + 1, dataEnd, depth + 1) ;
}

/** ------------------------------------------------------------------
 ** @brief Create new KDForest object
 ** @param numDimensions data dimensionality.
 ** @param numTrees number of trees in the forest.
 ** @return new KDForest.
 **/

VL_EXPORT
VlKDForest *
vl_kdforest_new (int unsigned numDimensions, int unsigned numTrees)
{
  VlKDForest * self = vl_malloc (sizeof(VlKDForest)) ;

  self -> numData = 0 ;
  self -> data = 0 ;
  self -> numDimensions = numDimensions ;
  self -> numTrees = numTrees ;
  self -> trees = 0 ;
  self -> thresholdingMethod = VL_KDTREE_MEDIAN ;
  self -> splitHeapSize = (numTrees == 1) ? 1 : VL_KDTREE_SPLIT_HEALP_SIZE ;
  self -> splitHeapNumNodes = 0 ;

  self -> searchHeapArray = 0 ;
  self -> searchHeapNumNodes = 0 ;


  self -> searchMaxNumComparisons = 0 ;
  self -> searchIdBook = 0 ;
  self -> searchId = 0 ;

  return self ;
}

/** ------------------------------------------------------------------
 ** @brief Delete KDForest object
 ** @param tree KDForest object to delete
 ** @sa ::vl_kdforest_new
 **/

VL_EXPORT void
vl_kdforest_delete (VlKDForest * self)
{
  int ti ;
  if (self->searchIdBook) vl_free (self->searchIdBook) ;
  if (self->trees) {
    for (ti = 0 ; ti < self->numTrees ; ++ ti) {
      if (self->trees[ti]) {
        if (self->trees[ti]->nodes) vl_free (self->trees[ti]->nodes) ;
        if (self->trees[ti]->dataIndex) vl_free (self->trees[ti]->dataIndex) ;
      }
    }
    vl_free (self->trees) ;
  }
  vl_free (self) ;
}

/** ------------------------------------------------------------------
 ** @brief Build KDTree from data
 ** @param tree KDTree object
 ** @param numData number of data points.
 ** @param data pointer to the data.
 **
 ** The function builds the KDTree by processing the data @a data. For
 ** efficiency, KDTree does not copy the data, but retains a pointer to it.
 ** Therefore the data must survive (and not change) until the KDTree
 ** is deleted.
 **/

VL_EXPORT void
vl_kdforest_build (VlKDForest * self, int numData, float const * data)
{
  int di, ti ;

  /* need to check: if alredy built, clean first */
  self->data = data ;
  self->numData = numData ;
  self->trees = vl_malloc (sizeof(VlKDTree*) * self->numTrees) ;

  for (ti = 0 ; ti < self->numTrees ; ++ ti) {
    self->trees[ti] = vl_malloc (sizeof(VlKDTree)) ;
    self->trees[ti]->dataIndex = vl_malloc (sizeof(VlKDTreeDataIndexEntry) * self->numData) ;
    for (di = 0 ; di < self->numData ; ++ di) {
      self->trees[ti]->dataIndex[di].index = di ;
    }
    self->trees[ti]->numUsedNodes = 0 ;
    /* num. nodes of a complete binary tree with numData leaves */
    self->trees[ti]->numAllocatedNodes = 2 * self->numData - 1 ;
    self->trees[ti]->nodes = vl_malloc (sizeof(VlKDTreeNode) * self->trees[ti]->numAllocatedNodes) ;
    self->trees[ti]->depth = 0 ;
    vl_kdtree_build_recursively (self, self->trees[ti],
                                 vl_kdtree_node_new(self->trees[ti], 0), 0,
                                 self->numData, 0) ;
  }
}

/** ------------------------------------------------------------------
 ** @internal @brief
 **/

VL_INLINE
float calc_dist2 (float const * a, float const * b, int unsigned N)
{
  float acc = 0 ;
  float d0, d1, d2, d3 ;
  float const * age = a + N - 3 ;
  float const * ae = a + N ;

  while (a < age) {
    d0 = *a++ - *b++ ;
    d1 = *a++ - *b++ ;
    d2 = *a++ - *b++ ;
    d3 = *a++ - *b++ ;
    acc += d0 * d0 ;
    acc += d1 * d1 ;
    acc += d2 * d2 ;
    acc += d3 * d3 ;
  }
  while (a < ae) {
    d0 = *a++ - *b++ ;
    acc += d0 * d0 ;
  }
  return acc ;
}

/** ------------------------------------------------------------------
 ** @internal @brief
 **/

VL_EXPORT int
vl_kdforest_query_recursively (VlKDForest  * self,
                               VlKDTree * tree,
                               int unsigned nodeIndex,
                               VlKDForestNeighbor * neighbors,
                               int unsigned numNeighbors,
                               int unsigned * numAddedNeighbors,
                               float dist,
                               float const * query)
{
  VlKDTreeNode const * node = tree->nodes + nodeIndex ;
  int unsigned i = node->splitDimension ;
  int nextChild, saveChild ;
  float delta, saveDist ;
  float x = query [i] ;
  float x1 = node->lowerBound ;
  float x2 = node->splitThreshold ;
  float x3 = node->upperBound ;
  VlKDForestSearchState * searchState ;

  self->searchNumRecursions ++ ;

  /* base case: this is a leaf node */
  if (node->lowerChild < 0) {
    int begin = - node->lowerChild - 1 ;
    int end   = - node->upperChild - 1 ;
    int iter ;

    for (iter = begin ;
         iter < end &&
         (self->searchMaxNumComparisons == 0 ||
          self->searchNumComparisons < self->searchMaxNumComparisons) ;
         ++ iter) {

      int unsigned di = tree->dataIndex [iter].index ;
      float const * datum = self->data + di * self->numDimensions ;

      /* multiple KDTrees share the database points and we must avoid
       * adding the same point twice */
      if (self->searchIdBook [di] == self->searchId) continue ;
      self->searchIdBook [di] = self->searchId ;

      /* compare the query to this point */
      dist = calc_dist2 (query, datum, self->numDimensions) ;
      self->searchNumComparisons += 1 ;

      /* see if it should be added to the result set */
      if (*numAddedNeighbors < numNeighbors) {
        VlKDForestNeighbor * newNeighbor = neighbors + *numAddedNeighbors ;
        newNeighbor->index = di ;
        newNeighbor->distance = dist ;
        vl_kdforest_neighbor_heap_push (neighbors, numAddedNeighbors) ;
      } else {
        VlKDForestNeighbor * largestNeighbor = neighbors + 0 ;
        if (largestNeighbor->distance > dist) {
          largestNeighbor->index = di ;
          largestNeighbor->distance = dist ;
          vl_kdforest_neighbor_heap_update (neighbors, *numAddedNeighbors, 0) ;
        }
      }
    } /* next data point */

    return nodeIndex ;
  }

#if 0
  assert (x1 <= x2 && x2 <= x3) ;
  assert (node->lowerChild >= 0) ;
  assert (node->upperChild >= 0) ;
#endif

  /*
   *   x1  x2 x3
   * x (---|---]
   *   (--x|---]
   *   (---|x--]
   *   (---|---] x
   */

  delta = x - x2 ;
  saveDist = dist + delta*delta ;

  if (x <= x2) {
    nextChild = node->lowerChild ;
    saveChild = node->upperChild ;
    if (x <= x1) {
      delta = x - x1 ;
      saveDist -= delta*delta ;
    }
  } else {
    nextChild = node->upperChild ;
    saveChild = node->lowerChild ;
    if (x > x3) {
      delta = x - x3 ;
      saveDist -= delta*delta ;
    }
  }

  if (*numAddedNeighbors < numNeighbors || neighbors[0].distance > saveDist) {
    searchState = self->searchHeapArray + self->searchHeapNumNodes ;
    searchState->tree = tree ;
    searchState->nodeIndex = saveChild ;
    searchState->distanceLowerBound = saveDist ;
    vl_kdforest_search_heap_push (self->searchHeapArray,
                                  &self->searchHeapNumNodes) ;
  }

  return vl_kdforest_query_recursively (self,
                                        tree,
                                        nextChild,
                                        neighbors,
                                        numNeighbors,
                                        numAddedNeighbors,
                                        dist,
                                        query) ;
}

/** ------------------------------------------------------------------
 ** @internal @brief Compute tree bounds recursively
 ** @param self KDTree object instance.
 ** @param nodeIndex node index to start from.
 ** @param searchBounds 2 x numDimension array of bounds.
 **/

static void
vl_kdtree_calc_bounds_recursively (VlKDTree * tree,
                                   int unsigned nodeIndex, float * searchBounds)
{
  VlKDTreeNode * node = tree->nodes + nodeIndex ;
  int unsigned i = node->splitDimension ;
  float t = node->splitThreshold ;

  node->lowerBound = searchBounds [2 * i + 0] ;
  node->upperBound = searchBounds [2 * i + 1] ;

  if (node->lowerChild > 0) {
    searchBounds [2 * i + 1] = t ;
    vl_kdtree_calc_bounds_recursively (tree, node->lowerChild, searchBounds) ;
    searchBounds [2 * i + 1] = node->upperBound ;
  }
  if (node->upperChild > 0) {
    searchBounds [2 * i + 0] = t ;
    vl_kdtree_calc_bounds_recursively (tree, node->upperChild, searchBounds) ;
    searchBounds [2 * i + 0] = node->lowerBound ;
  }
}

/** ------------------------------------------------------------------
 ** @brief Query operation
 ** @param self KDTree object instance.
 ** @param neighbors list of nearest neighbors found (output).
 ** @param numNeighbors number of nearest neighbors to find.
 ** @param query query point.
 ** @return number of tree leaves visited.
 **
 ** A neighbor is represented by an instance of the structure
 ** ::VlKDForestNeighbor. Each entry contains the index of the
 ** neighbor (this is an index into the KDTree data) and its distance
 ** to the query point. Neighbors are sorted by increasing distance.
 **/

VL_EXPORT int
vl_kdforest_query (VlKDForest * self,
                   VlKDForestNeighbor * neighbors,
                   int unsigned numNeighbors,
                   float const * query)
{
  int i, ti ;
  vl_bool exactSearch = (self->searchMaxNumComparisons == 0) ;
  VlKDForestSearchState * searchState  ;
  int unsigned numAddedNeighbors = 0 ;

  assert (neighbors) ;
  assert (numNeighbors > 0) ;
  assert (query) ;

  /* this number is used to differentiate a query from the next */
  self -> searchId += 1 ;
  self -> searchNumRecursions = 0 ;

  if (! self -> searchHeapArray) {
    /* count number of tree nodes */
    /* add support structures */
    int maxNumNodes = 0 ;
    for (ti = 0 ; ti < self->numTrees ; ++ti) {
      maxNumNodes += self->trees[ti]->numUsedNodes ;
    }
    self -> searchHeapArray = vl_malloc (sizeof(VlKDForestSearchState) * maxNumNodes) ;
    self -> searchIdBook = vl_calloc (sizeof(unsigned int), self->numData) ;

    for (ti = 0 ; ti < self->numTrees ; ++ti) {
      float * searchBounds = vl_malloc(sizeof(float) * 2 * self->numDimensions) ;
      float * iter = searchBounds  ;
      float * end = iter + 2 * self->numDimensions ;
      while (iter < end) {
        *iter++ = - VL_INFINITY_F ;
        *iter++ = + VL_INFINITY_F ;
      }
      vl_kdtree_calc_bounds_recursively (self->trees[ti], 0, searchBounds) ;
      vl_free (searchBounds) ;
    }
  }

  self->searchNumComparisons = 0 ;
  self->searchNumSimplifications = 0 ;

  /* put the root node into the search heap */
  self->searchHeapNumNodes = 0 ;
  for (ti = 0 ; ti < self->numTrees ; ++ ti) {
    searchState = self->searchHeapArray + self->searchHeapNumNodes ;
    searchState -> tree = self->trees[ti] ;
    searchState -> nodeIndex = 0 ;
    searchState -> distanceLowerBound = 0 ;
    vl_kdforest_search_heap_push (self->searchHeapArray, &self->searchHeapNumNodes) ;
  }

  /* branch and bound */
  while (exactSearch || self->searchNumComparisons < self->searchMaxNumComparisons)
  {
    /* pop the next optimal search node */
    VlKDForestSearchState * searchState = vl_kdforest_search_heap_pop
      (self->searchHeapArray, &self->searchHeapNumNodes) ;

    /* break if search space completed */
    if (searchState == NULL) {
      break ;
    }

    /* break if no better solution may exist */
    if (numAddedNeighbors == numNeighbors &&
        neighbors[0].distance < searchState->distanceLowerBound) {
      self->searchNumSimplifications ++ ;
      break ;
    }

    vl_kdforest_query_recursively (self,
                                   searchState->tree,
                                   searchState->nodeIndex,
                                   neighbors,
                                   numNeighbors,
                                   &numAddedNeighbors,
                                   searchState->distanceLowerBound,
                                   query) ;
  }

  /* sort neighbors by increasing distance */
  for (i = numAddedNeighbors ;  i < numNeighbors ; ++ i) {
    neighbors[i].index = -1 ;
    neighbors[i].distance = VL_NAN_F ;
  }
  while (numAddedNeighbors) {
    vl_kdforest_neighbor_heap_pop (neighbors, &numAddedNeighbors) ;
  }

  return self->searchNumComparisons ;
}