Algorithm Search⌘K

Algorithmadvanced

Best bin first search

Also called BBF search.

Approximate nearest neighbor search in a k-d tree that visits bins in order of distance from the query, from a priority queue, and stops after a fixed number of leaves.

Time
O(E log n (d + log(E log n)) + E log k) worst · averageO(d log n) best
Space
O(E d log n + k) extra
Where
E = the number of leaves to examine; d = the dimension; k = the number of neighbors; n = the number of points
Properties
anytimedeterministicnot exactexact when unbounded
Origin
Jeffrey S. Beis, David G. Lowe, 1997

Best bin first (BBF) search finds an approximate nearest neighbor of a query point in a k-d tree. It keeps the subtrees it has not explored in a priority queue, keyed by the distance from the query to the box (the bin) of each subtree, and always explores the closest bin next. It stops after a fixed number EE of leaves and returns the best point found so far, so in high dimension the answer can be wrong; with no limit it is the exact search. Beis and Lowe (1997) introduced it for shape indexing, and Lowe used it to match SIFT descriptors.

In plain words

A k-d tree cuts space into boxes, and each box holds a few points. To find the point closest to a query, the plain search goes down to the box that holds the query and then backs up the tree and looks at the neighboring boxes in the order of the tree. In many dimensions the true answer is often in a box far from that order, and the exact search ends up looking at most of the boxes. BBF looks at boxes in the order of their distance from the query instead. It keeps a list of boxes not yet seen, sorted by distance, and takes the closest one each time. Most of the time the true answer is in one of the first boxes it sees. So BBF looks at a fixed number of boxes, for example 200, and returns the best point among them.

The problem

The input is a set of nn points x(1),…,x(n)x^{(1)}, \dots, x^{(n)} in Rd\mathbb{R}^d, a query qq, a number of neighbors kk and a budget of EE leaves. The output is a list of kk points of the set with their squared Euclidean distances D(x)=∥x−q∥2D(x) = \lVert x - q \rVert^2 to qq, sorted. The ideal answer is the kk nearest points. BBF gives that answer when EE is large enough, and otherwise a list of points that are close but not always the closest. This is a form of approximate nearest neighbor search with no guarantee on the error; the c-approximate form has a guarantee.

The tree is the one of Beis and Lowe. Each internal node takes the dimension of greatest variance of its points, sorts them on that dimension and splits at the median point. The left child gets the first half, with coordinates at most the split value ss, and the right child gets the rest, with coordinates at least ss. A leaf holds one point in the paper; our code allows a few. The depth is ⌈log⁡2n⌉\lceil \log_2 n \rceil with one point per leaf.

The algorithm

Each queue entry is a subtree, its key bb and an offset vector oo. The offset oto_t is the signed distance from qq to the last split on dimension tt that the path crossed to the far side, or 0. The key is b=∑tot2b = \sum_t o_t^2, the squared distance from qq to the bin of the subtree. A crossing on dimension jj changes one term of the sum, so the new key costs O(1)O(1) arithmetic plus the copy of oo.

  1. BBF-SEARCH(T, q, E, k)
  2. 1best ← empty list of at most k (distance, point) pairs; checked ← 0
  3. 2Q ← min-priority queue holding (0, root of T, zero offsets)
  4. 3while Q is not empty and checked < E do
  5. 4(b, node, o) ← remove the entry with the smallest key from Q
  6. 5if best has k items and b ≥ the largest distance in best then stop: the answer is exact
  7. 6while node is an internal node do
  8. 7j ← split dimension of node; δ ← q_j - split value of node
  9. 8if δ < 0 then near, far ← left, right else near, far ← right, left
  10. 9o' ← o with o'_j = δ; b' ← b - o_j^2 + δ^2
  11. 10insert (b', far, o') into Q
  12. 11node ← near
  13. 12for each point x in the leaf node: put (D(x), x) in best if it is among the k closest so far
  14. 13checked ← checked + 1
  15. 14return best

The descent of lines L6 to L11 keeps the key bb for the near child, because the query is on the near side of the split. Line L5 is the stop rule of the exact search: no unexplored bin is closer than the current kk-th neighbor. With E=∞E = \infty, BBF is the exact k-d tree nearest neighbor search that visits the bins in order of distance instead of in the order of the tree.

The original paper describes the queue key as the distance from the query to the bin boundary. Some implementations use only the squared distance to the last split hyperplane, δ2\delta^2. That key is also a lower bound, but a weaker one, so it explores more bins before line L5 stops the search. Our code uses the full bin distance.

Example

Take the six points (2,3)(2, 3), (5,4)(5, 4), (9,6)(9, 6), (4,7)(4, 7), (8,1)(8, 1), (7,2)(7, 2) in the plane, with one point per leaf. The variance of the xx coordinates is 5.815.81 and of the yy coordinates 4.474.47, so the root splits on xx. Sorted on xx, the median point is (7,2)(7, 2), so the root splits at x=7x = 7. The left half {(2,3),(4,7),(5,4)}\{(2,3), (4,7), (5,4)\} splits on yy at 4, and its right part {(5,4),(4,7)}\{(5,4), (4,7)\} splits on yy at 7. The right half {(7,2),(8,1),(9,6)}\{(7,2), (8,1), (9,6)\} splits on yy at 2, and its right part {(7,2),(9,6)}\{(7,2), (9,6)\} splits on yy at 6.

The query is q=(4.5,1)q = (4.5, 1). Squared distances are used throughout.

step popped key leaf reached pushed (key, bin) best so far
1 0 (2, 3), distance 10.25 (6.25, x≥7x \ge 7), (9, x≤7,y≥4x \le 7, y \ge 4) (2, 3), 10.25
2 6.25 (8, 1), distance 12.25 (7.25, x≥7,y≥2x \ge 7, y \ge 2) (2, 3), 10.25
3 7.25 (7, 2), distance 7.25 (31.25, x≥7,y≥6x \ge 7, y \ge 6) (7, 2), 7.25
4 9 none none stop: 9≥7.259 \ge 7.25

In step 1 the root has δ=4.5−7=−2.5\delta = 4.5 - 7 = -2.5, so the key of the right half is 2.52=6.252.5^2 = 6.25. The node below has δ=1−4=−3\delta = 1 - 4 = -3, so its far child gets 0+9=90 + 9 = 9. In step 2 the popped entry has the offset −2.5-2.5 on xx, and the split y=2y = 2 gives δ=−1\delta = -1, so the far child gets 6.25+1=7.256.25 + 1 = 7.25. In step 4 the smallest key, 9, is at least the best distance, 7.25, so line L5 stops: the answer (7,2)(7, 2) is exact after 3 leaves. With E=1E = 1 the search returns (2,3)(2, 3), the plain descent, at distance 10.25=3.20\sqrt{10.25} = 3.20 instead of 7.25=2.69\sqrt{7.25} = 2.69; with E=2E = 2 it still returns (2,3)(2, 3).

A measured example: we ran our code on 5000 points uniform in [0,1]d[0, 1]^d, with 100 uniform queries, one point per leaf and seed 7. The table gives the number of queries, out of 100, for which BBF returned the true nearest neighbor, and the mean ratio of the returned distance to the true distance.

dd E=1E = 1 E=10E = 10 E=50E = 50 E=200E = 200 leaves to prove the answer exact (mean)
4 15, 1.914 88, 1.020 100, 1.000 100, 1.000 16.5
8 14, 1.562 60, 1.097 96, 1.003 100, 1.000 129.4
16 6, 1.422 32, 1.121 58, 1.039 89, 1.007 2470.6

In 16 dimensions the exact search must examine about half of the 5000 leaves, but 200 leaves give the true neighbor 89 times out of 100. This is a measurement on one random data set, not a property of the method.

Correctness

The proof in proofs/correctness.md shows four facts:

  • The key is a lower bound. For every queue entry (b,v,o)(b, v, o), every point xx in the subtree of vv has ∣xt−qt∣≥∣ot∣|x_t - q_t| \ge |o_t| for each tt, so D(x)≥bD(x) \ge b.
  • The keys come out in order. A crossing on dimension jj never makes ∣oj∣|o_j| smaller, because each split value is a coordinate of a point inside the bin. So the popped keys do not decrease, and BBF examines the bins in order of distance.
  • Exact when it stops by itself. If the queue is empty, or line L5 stops the loop, the list holds the kk nearest points.
  • More leaves do not hurt. The search with budget EE examines a prefix of the leaves that the search with budget E′>EE' > E examines, so its ii-th distance is never smaller.

There is no bound on the error when the budget stops the search. The success rates in the example and in the papers are measurements.

Proof: Correctness of best bin first searchfull

Fix a finite set of points x(1),…,x(n)x^{(1)}, \dots, x^{(n)} in Rd\mathbb{R}^d, a query qq, a number k≥1k \ge 1 and a leaf budget E≥1E \ge 1, possibly E=∞E = \infty. The tree is the k-d tree of the main page. Each internal node vv has a split dimension dvd_v and a split value svs_v, which is a coordinate of a point of its subtree. Every point xx in the left subtree of vv has xdv≤svx_{d_v} \le s_v, and every point in the right subtree has xdv≥svx_{d_v} \ge s_v. A queue entry is a triple (b,v,o)(b, v, o) with a number bb, a node vv and an offset vector o∈Rdo \in \mathbb{R}^d. Distances below are squared Euclidean distances, D(x)=∥x−q∥2D(x) = \lVert x - q \rVert^2.

Lemma 1 (the bound). For every entry (b,v,o)(b, v, o) that line L2 or line L10 puts in the queue, b=∑tot2b = \sum_t o_t^2, and every point xx in the subtree of vv has ∣xt−qt∣≥∣ot∣|x_t - q_t| \ge |o_t| for each tt. Hence D(x)≥bD(x) \ge b.

Proof. Line L2 puts (0,root,0)(0, \text{root}, 0) in the queue, and both claims hold. Assume the claims for an entry (b,v,o)(b, v, o) that line L4 pops. Lines L6 to L11 walk down from vv and keep bb and oo. Each node ww on this walk is in the subtree of vv, so the points of its subtree also satisfy ∣xt−qt∣≥∣ot∣|x_t - q_t| \ge |o_t|. At ww, with j=dwj = d_w and δ=qj−sw\delta = q_j - s_w, line L10 pushes the far child with o′o', where oj′=δo'_j = \delta and ot′=oto'_t = o_t for t≠jt \ne j, and with b′=b−oj2+δ2=∑tot′2b' = b - o_j^2 + \delta^2 = \sum_t o_t'^2. For t≠jt \ne j the claim for the far child follows from the claim for ww. For t=jt = j there are two cases. If δ<0\delta < 0, the far child is the right child, so each of its points has xj≥sw>qjx_j \ge s_w > q_j and ∣xj−qj∣=xj−qj≥sw−qj=∣δ∣|x_j - q_j| = x_j - q_j \ge s_w - q_j = |\delta|. If δ≥0\delta \ge 0, the far child is the left child, so xj≤sw≤qjx_j \le s_w \le q_j and ∣xj−qj∣=qj−xj≥qj−sw=δ|x_j - q_j| = q_j - x_j \ge q_j - s_w = \delta. In both cases ∣xj−qj∣≥∣oj′∣|x_j - q_j| \ge |o'_j|. Then D(x)=∑t(xt−qt)2≥∑tot′2=b′D(x) = \sum_t (x_t - q_t)^2 \ge \sum_t o_t'^2 = b'. □\square

Lemma 2 (the partition). At each test of line L3, every leaf of the tree is either a leaf that line L12 has examined or a leaf in the subtree of exactly one queue entry, and not both.

Proof. At the start the queue holds the root and no leaf is examined. When line L4 pops (b,v,o)(b, v, o), the leaves of the subtree of vv are no longer covered by the queue. The walk of lines L6 to L11 goes from vv to one leaf, and at each node it pushes the subtree of the other child. The subtrees of the pushed children and the final leaf partition the leaves of the subtree of vv, and line L12 examines the final leaf. So the claim holds again at the next test of line L3. □\square

Lemma 3 (the order). Let bb be the key that line L4 pops. Every entry that lines L6 to L11 push has a key b′≥bb' \ge b. Hence the keys that line L4 pops do not decrease.

Proof. Use the notation of Lemma 1. If oj=0o_j = 0, then b′=b+δ2≥bb' = b + \delta^2 \ge b. If oj<0o_j < 0, an earlier crossing on dimension jj put the subtree of ww on the side xj≥s′>qjx_j \ge s' > q_j of an earlier split s′s', with oj=qj−s′o_j = q_j - s'. The split value sws_w is a coordinate of a point of this subtree, so sw≥s′>qjs_w \ge s' > q_j. Then δ=qj−sw≤qj−s′=oj<0\delta = q_j - s_w \le q_j - s' = o_j < 0 and δ2≥oj2\delta^2 \ge o_j^2. The case oj>0o_j > 0 is symmetric. So b′=b−oj2+δ2≥bb' = b - o_j^2 + \delta^2 \ge b. The queue is a min-priority queue, so after the pop every entry in it has a key at least bb, and the new entries also have keys at least bb. So the next pop has a key at least bb. □\square

Lemma 4 (the best list). After each execution of line L12, the list holds the min⁡(k,m)\min(k, m) smallest distances among the mm points of the examined leaves, with their indices.

Proof. Line L1 starts with an empty list. Line L12 takes each new point and keeps it if the list has fewer than kk items or if the point is closer than the worst item, which it then replaces. This is the standard bounded selection with a max-heap, so the claim holds by induction over the points. □\square

Theorem 1 (exact answer). If the loop ends because the queue is empty or because of the test of line L5, the list that line L14 returns holds the kk smallest distances D(x)D(x) over all points, or all nn points if n<kn < k.

Proof. If the queue is empty, Lemma 2 says that every leaf is examined, and Lemma 4 gives the claim. If line L5 stops the loop, the list has kk items, and the popped key bb is at least the largest distance rr in the list. The popped entry and every entry still in the queue have keys at least bb, because the queue is a min-priority queue. By Lemma 2 each point that is not examined is in the subtree of one of these entries, and by Lemma 1 its distance is at least b≥rb \ge r. So no point outside the list is closer than the kk-th item of the list, and with Lemma 4 the list holds the kk smallest distances. □\square

Theorem 2 (more leaves do not hurt). Let E<E′E < E'. Let ri(E)r_i(E) be the ii-th distance in the list that the search returns with budget EE. Then ri(E′)≤ri(E)r_i(E') \le r_i(E) for each ii for which both are defined.

Proof. The steps of the search depend on the budget only through the test at line L3. So the run with budget EE does the same steps as the run with budget E′E' until it stops, and the leaves that it examines are the first leaves that the run with E′E' examines. The run with E′E' examines a superset of points. By Lemma 4 each run returns the smallest distances of its examined set, and the ii-th smallest value of a superset is at most the ii-th smallest value of the subset. □\square

Remark (what is not proved). When the budget EE stops the loop, the answer can be wrong, and the page gives no bound on the error. The success rates on the main page are measurements, not consequences of these lemmas. The key bb is in fact the squared distance from qq to the box of the leaf cell, because by Lemma 3 the last crossing on each dimension is the tightest one, but the proofs above use only the lower bound of Lemma 1. ■\blacksquare

Complexity

The model is the real RAM, with one arithmetic operation or comparison on reals at unit cost. Let h=⌈log⁡2n⌉h = \lceil \log_2 n \rceil be the depth of the tree.

  • Build. At each of the hh levels the code computes dd variances over all points and sorts each node on one dimension, which costs O(dn+nlog⁡n)O(d n + n \log n) per level and O(dnlog⁡n+nlog⁡2n)O(d n \log n + n \log^2 n) in total. A linear-time median brings this to O(dnlog⁡n)O(d n \log n).
  • Search. Each of the EE examined leaves comes from one descent of at most hh levels. Each level pushes one entry: O(d)O(d) to copy the offsets and O(log⁡(Eh))O(\log(E h)) for the heap. Each leaf point costs O(d)O(d) for the distance and O(log⁡k)O(\log k) for the list. With a constant number of points per leaf, the total is O(Eh(d+log⁡(Eh))+Elog⁡k)O(E h (d + \log(E h)) + E \log k), and the queue holds at most EhE h entries of d+2d + 2 numbers.
  • Best case. With E=1E = 1 the search is the plain descent, O(dlog⁡n)O(d \log n).

The cost depends on EE and not on how far the true neighbor is. This is the point of BBF: a fixed time per query. The exact search, by contrast, has a good expected cost only in low dimension. Friedman, Bentley and Finkel (1977) showed a logarithmic expected time for a fixed dimension, with a constant that grows exponentially with dd; in high dimension the exact search examines a large part of the leaves, as the table above shows.

Beis and Lowe measured this on 100,000 points uniform in the unit hypercube with E=200E = 200 and 1000 queries. In 12 dimensions BBF found the true nearest neighbor 94 percent of the time, against 59 percent for the restricted search in the order of the tree, which they allowed 2.4 times as many leaves. The exact search examined over 2400 leaves. Up to 20 dimensions the mean distance that BBF found was only 2 percent greater than the true one. Lowe (2004) stopped BBF after 200 candidates to match SIFT keypoints against 100,000 keypoints and measured a speedup of about two orders of magnitude over exact search, with a loss of less than 5 percent of the correct matches.

Properties

  • Anytime. The search can stop after any number of leaves and returns the best points found so far. More leaves never give a worse answer.
  • Exact with no limit. With E=∞E = \infty the result is the exact kk nearest neighbors, and the search often proves this early through line L5.
  • Deterministic. For a fixed tree and query, the order of the leaves is fixed. Ties in the queue are broken by the insertion order.
  • No error bound. Unlike the (1+ε)(1 + \varepsilon) search of Arya and his coauthors, the fixed budget gives no bound on the ratio of distances.
  • Works for k>1k > 1. The list keeps kk neighbors, which the ratio test needs with k=2k = 2.

Variants and improvements

  • Priority search with an error bound. Arya, Mount, Netanyahu, Silverman and Wu stop when the key exceeds the best distance divided by (1+ε)2(1 + \varepsilon)^2, and prove that the result is within a factor 1+ε1 + \varepsilon of the true distance. Their tree is the balanced box decomposition tree.
  • Hyperplane key. Use δ2\delta^2 of the last split as the key. It costs less memory, since no offset vector is stored, but the key is a weaker bound.
  • Many trees. The randomized k-d forest builds several trees with random split dimensions and searches all of them with one queue. In the measurements of Silpa-Anan and Hartley and of Muja and Lowe on SIFT descriptors, this does better than one tree at the same number of checks.
  • Other indexes. Locality-sensitive hashing, product quantization and graph indexes such as HNSW replace the tree in large systems.
  • Branch and bound. BBF is best-first branch and bound with the bin distance as the bound and a limit on the number of nodes.

When to use it

Use BBF when you need nearest neighbors of many queries in a fixed set of moderate dimension, about 8 to 30, and a fixed time per query matters more than a guarantee. The classic case is feature matching of SIFT descriptors, where a wrong neighbor only loses one match and RANSAC removes it later. In 2 or 3 dimensions use the exact search; it is fast there. For millions of points in high dimension, a forest of trees or a graph index usually gives a better trade of time and accuracy.

Pitfalls

  • Squared distances. Keep squared distances in the queue and in the list. A ratio threshold on distances, such as 0.8, becomes 0.64 on squared distances.
  • The key must be a lower bound. If the key overestimates the distance to the bin, the stop rule of line L5 can stop too early and claim an exact answer that is wrong. Adding δ2\delta^2 to the key without removing the old offset on the same dimension overestimates.
  • Budget in leaves or in points. Beis and Lowe count leaves; FLANN counts the points it checks. With one point per leaf they agree; with larger leaves they do not.
  • No guarantee. With a budget the result can be wrong. Report the budget with any accuracy number.
  • Ties at the split. Points equal to the split value can be on both sides. Keep the order ≤s\le s on the left and ≥s\ge s on the right, or the lower bound on the key fails.
  • Duplicates. Many equal points have zero variance in every dimension. Stop the split there and keep them in one leaf, or the build does not end.

Implementations

The Python code in impl/python/best_bin_first_search.py builds the tree of Beis and Lowe and runs BBF with the full bin distance and a budget in leaves. It returns the kk nearest points it found and a flag that is true when line L5 or an empty queue proved the answer exact. The tests compare the unbounded search with a brute force scan in 1 to 8 dimensions, check that the flag is never wrong, check that the keys are lower bounds and come out in order, and check that a larger budget never gives a worse answer.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

best_bin_first_search.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/best-bin-first-search/. The authors are listed in prov/THZZ2G.jsonl.

"""Best bin first (BBF) search in a k-d tree (Beis and Lowe 1997).

Points are tuples of floats of the same dimension d. The tree is the
standard k-d tree of Beis and Lowe: each internal node splits on the
dimension of greatest variance of its points, at the median point. A leaf
holds at most `leaf_size` points (1 in the paper).

The search keeps a min-priority queue of subtrees that it has not explored.
The key of a subtree is the squared distance from the query to its bin (the
box of points that the subtree can hold), so the queue gives the bins in
order of increasing distance. The search stops after it has examined
`max_leaves` leaves, which makes it approximate, or when the next bin is
not closer than the current k-th neighbor, which makes the answer exact.

The bin distance is kept with one offset per dimension: the signed distance
from the query to the last split on that dimension that the path crossed to
the far side. The squared distance to the bin is the sum of the squared
offsets, and one crossing changes one term (Arya and Mount 1993).
"""

import heapq
import math
from typing import List, Optional, Sequence, Tuple

Point = Tuple[float, ...]


class Node:
    __slots__ = ("dim", "split", "left", "right", "ids")

    def __init__(self, dim=-1, split=0.0, left=None, right=None, ids=None):
        self.dim = dim  # split dimension, -1 for a leaf
        self.split = split  # left points have x[dim] <= split, right points x[dim] >= split
        self.left = left
        self.right = right
        self.ids = ids  # point indices of a leaf


def _variance(points: Sequence[Point], ids: Sequence[int], d: int) -> float:
    m = sum(points[i][d] for i in ids) / len(ids)
    return sum((points[i][d] - m) ** 2 for i in ids) / len(ids)


def build(points: Sequence[Point], leaf_size: int = 1) -> Optional[Node]:
    """Build the k-d tree of Beis and Lowe: split at the median on the dimension of greatest variance."""
    if not points:
        return None
    dim = len(points[0])

    def make(ids: List[int]) -> Node:
        if len(ids) <= leaf_size:
            return Node(ids=ids)
        var = [_variance(points, ids, d) for d in range(dim)]
        best = max(range(dim), key=lambda d: (var[d], -d))
        if var[best] == 0.0:  # all points equal: one leaf
            return Node(ids=ids)
        ids = sorted(ids, key=lambda i: (points[i][best], i))
        mid = len(ids) // 2
        split = points[ids[mid]][best]
        return Node(best, split, make(ids[:mid]), make(ids[mid:]))

    return make(list(range(len(points))))


def sqdist(p: Sequence[float], q: Sequence[float]) -> float:
    return sum((a - b) * (a - b) for a, b in zip(p, q))


def bbf_search(
    root: Optional[Node],
    points: Sequence[Point],
    q: Sequence[float],
    k: int = 1,
    max_leaves: float = math.inf,
    log: Optional[list] = None,
) -> Tuple[List[Tuple[float, int]], bool]:
    """Return (neighbors, exact).

    neighbors is the list of up to k pairs (squared distance, index), sorted.
    exact is True when the search proved that the list is the true k nearest.
    If log is a list, the search appends (bin distance, leaf ids) for each leaf.
    """
    best: List[Tuple[float, int]] = []  # max-heap by (-dist, -index)  # @line L1
    checked = 0
    if root is None:
        return [], True
    d = len(q)
    count = 0
    queue = [(0.0, count, root, (0.0,) * d)]  # @line L2
    exact = True
    while queue:  # @line L3
        if checked >= max_leaves:
            exact = False
            break
        b, _, node, off = heapq.heappop(queue)  # @line L4
        if len(best) == k and b >= -best[0][0]:  # @line L5
            break
        while node.dim >= 0:  # @line L6
            delta = q[node.dim] - node.split  # @line L7
            if delta < 0:  # @line L8
                near, far = node.left, node.right
            else:
                near, far = node.right, node.left
            old = off[node.dim]  # @line L9
            far_off = off[: node.dim] + (delta,) + off[node.dim + 1:]
            count += 1
            heapq.heappush(queue, (b - old * old + delta * delta, count, far, far_off))  # @line L10
            node = near  # @line L11
        if log is not None:
            log.append((b, list(node.ids)))
        for i in node.ids:  # @line L12
            dist = sqdist(points[i], q)
            item = (-dist, -i)
            if len(best) < k:
                heapq.heappush(best, item)
            elif item > best[0]:
                heapq.heapreplace(best, item)
        checked += 1  # @line L13
    return sorted((-nd, -ni) for nd, ni in best), exact  # @line L14


def brute_force(points: Sequence[Point], q: Sequence[float], k: int = 1) -> List[Tuple[float, int]]:
    """The k nearest points by a full scan, ties broken by the smaller index."""
    return sorted((sqdist(p, q), i) for i, p in enumerate(points))[:k]
test_best_bin_first_search.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/best-bin-first-search/. The authors are listed in prov/THZZ2G.jsonl.

import math
import random

from best_bin_first_search import bbf_search, brute_force, build, sqdist


def cloud(rng, n, d):
    return [tuple(rng.random() for _ in range(d)) for _ in range(n)]


def leaves(node):
    if node.dim < 0:
        return [node]
    return leaves(node.left) + leaves(node.right)


def test_tree_holds_every_point_once_and_respects_splits():
    rng = random.Random(1)
    for leaf_size in (1, 3):
        pts = cloud(rng, 150, 4)
        root = build(pts, leaf_size)
        ids = sorted(i for leaf in leaves(root) for i in leaf.ids)
        assert ids == list(range(len(pts)))

        def check(node, lo, hi):
            if node.dim < 0:
                assert len(node.ids) <= leaf_size
                for i in node.ids:
                    for t in range(4):
                        assert lo[t] <= pts[i][t] <= hi[t]
                return
            hl = list(hi)
            hl[node.dim] = node.split
            check(node.left, lo, hl)
            ll = list(lo)
            ll[node.dim] = node.split
            check(node.right, ll, hi)

        check(root, [-math.inf] * 4, [math.inf] * 4)


def test_unlimited_search_equals_brute_force():
    rng = random.Random(2)
    for d in (1, 2, 3, 5, 8):
        pts = cloud(rng, 120, d)
        root = build(pts, rng.choice((1, 2, 4)))
        for _ in range(25):
            q = tuple(rng.uniform(-0.2, 1.2) for _ in range(d))
            for k in (1, 2, 5):
                got, exact = bbf_search(root, pts, q, k)
                want = brute_force(pts, q, k)
                assert exact
                assert [g[0] for g in got] == [w[0] for w in want]


def test_many_small_inputs_with_ties_against_brute_force():
    rng = random.Random(9)
    for _ in range(600):
        d = rng.randint(1, 3)
        pts = [tuple(rng.randint(0, 4) for _ in range(d)) for _ in range(rng.randint(1, 12))]
        root = build(pts, rng.choice((1, 2, 3)))
        q = tuple(rng.randint(-1, 5) + rng.choice((0.0, 0.5)) for _ in range(d))
        k = rng.randint(1, 3)
        got, exact = bbf_search(root, pts, q, k)
        assert exact
        assert [g[0] for g in got] == [w[0] for w in brute_force(pts, q, k)]
        got1, _ = bbf_search(root, pts, q, k, max_leaves=1)
        assert all(sqdist(pts[i], q) == g for g, i in got1)


def test_exact_flag_is_never_wrong():
    rng = random.Random(3)
    pts = cloud(rng, 300, 6)
    root = build(pts)
    for _ in range(60):
        q = tuple(rng.random() for _ in range(6))
        for e in (1, 3, 10, 40):
            got, exact = bbf_search(root, pts, q, 2, max_leaves=e)
            if exact:
                assert [g[0] for g in got] == [w[0] for w in brute_force(pts, q, 2)]


def test_bin_distances_are_lower_bounds_and_do_not_decrease():
    rng = random.Random(4)
    pts = cloud(rng, 200, 5)
    root = build(pts, 2)
    for _ in range(30):
        q = tuple(rng.uniform(-0.5, 1.5) for _ in range(5))
        log = []
        bbf_search(root, pts, q, 1, log=log)
        prev = -1.0
        for b, ids in log:
            assert b >= prev - 1e-12
            prev = b
            for i in ids:
                assert sqdist(pts[i], q) >= b - 1e-12


def test_more_leaves_never_give_a_worse_answer():
    rng = random.Random(5)
    pts = cloud(rng, 400, 10)
    root = build(pts)
    for _ in range(20):
        q = tuple(rng.random() for _ in range(10))
        last = math.inf
        for e in range(1, 60, 3):
            got, _ = bbf_search(root, pts, q, 1, max_leaves=e)
            assert got[0][0] <= last
            last = got[0][0]


def test_one_leaf_is_the_plain_descent():
    rng = random.Random(6)
    pts = cloud(rng, 64, 3)
    root = build(pts)
    for _ in range(20):
        q = tuple(rng.random() for _ in range(3))
        node = root
        while node.dim >= 0:
            node = node.left if q[node.dim] < node.split else node.right
        got, _ = bbf_search(root, pts, q, 1, max_leaves=1)
        assert got == [(sqdist(pts[node.ids[0]], q), node.ids[0])]


def test_duplicates_and_empty_input():
    pts = [(0.5, 0.5)] * 5 + [(0.0, 1.0)]
    root = build(pts)
    got, exact = bbf_search(root, pts, (0.5, 0.4), 3)
    assert exact and [g[0] for g in got] == [w[0] for w in brute_force(pts, (0.5, 0.4), 3)]
    assert bbf_search(None, [], (0.0,), 1) == ([], True)

History

Friedman, Bentley and Finkel (1977) gave the exact k-d tree search, which backs up the tree and tests each bin against the ball of the current best distance. Beis and Lowe (1997) changed the order of the search to the order of bin distance and added the fixed number of leaves, for indexing of shape features of moderate dimension. They note that Arya, in a technical report, independently developed the same method under the name priority k-d tree search; Arya, Mount and their coauthors later proved error bounds for a related priority search. Lowe used BBF in SIFT to match keypoints against large databases. Silpa-Anan and Hartley (2008) and Muja and Lowe (2009) extended it to several randomized trees.

References

  1. Jeffrey S. Beis and David G. Lowe, Shape indexing using approximate nearest-neighbour search in high-dimensional spaces, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 1997, 1000-1006, Section 4 (the k-d tree with median splits on the dimension of greatest variance, the BBF search with a priority queue and the limit Emax), Section 5 (the experiments on uniform data and on shape indexing)
  2. David G. Lowe, Distinctive image features from scale-invariant keypoints, International Journal of Computer Vision 60(2), 2004, 91-110, Section 7.2 (BBF with a cut-off after 200 candidates for keypoint matching)
  3. Sunil Arya, David M. Mount, Nathan S. Netanyahu, Ruth Silverman and Angela Y. Wu, An optimal algorithm for approximate nearest neighbor searching in fixed dimensions, Journal of the ACM 45(6), 1998, 891-923, the priority search of the leaf cells in order of distance from the query and the incremental distance computation
  4. Jerome H. Friedman, Jon Louis Bentley and Raphael Ari Finkel, An algorithm for finding best matches in logarithmic expected time, ACM Transactions on Mathematical Software 3(3), 1977, 209-226, the exact k-d tree search with the bounds-overlap-ball test that BBF reorders

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example