# R-tree

Implement an in-memory **R-tree**: a spatial index of axis-aligned rectangles
in two dimensions, each stored with an integer id, that finds the rectangles
intersecting a query rectangle and the rectangles nearest to a point.

This is the classic R-tree of Guttman (1984) with the **quadratic split**,
built and maintained one insertion and one removal at a time. It is **not**
an R*-tree (no forced reinsertion, no other split algorithm), an R+-tree, a
packed or Hilbert R-tree built by bulk loading, a quadtree, a k-d tree, a
grid, a list sorted along a space-filling curve, or a linear scan.

## Rectangles, ids and distances

- A **rectangle** is four integers `(x0, y0, x1, y1)` with
  `0 <= x0 <= x1 < 2^20` and `0 <= y0 <= y1 < 2^20`. It is closed: it
  contains the points `(x, y)` with `x0 <= x <= x1` and `y0 <= y <= y1`. A
  rectangle may be degenerate: a point (`x0 == x1` and `y0 == y1`) or a line.
- Two rectangles **intersect** when they share at least one point:
  `a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1`. Rectangles
  that only touch along an edge or at a corner intersect.
- The **area** of a rectangle is `(x1 - x0) * (y1 - y0)`, so points and lines
  have area 0. The **bounding rectangle** of a set of rectangles is the
  smallest rectangle that contains all of them. The **enlargement** needed for
  rectangle `R` to include rectangle `E` is `area(bounding rectangle of R and
  E) - area(R)`. Areas are below `2^40`, so they and their differences are
  computed exactly in 64-bit integers (and in JavaScript's plain numbers);
  every comparison of areas and enlargements below is exact.
- An **id** is an integer in `[0, 2^31)`. An **entry** is a rectangle with
  its id. The ids of the stored entries are distinct: the caller never
  inserts an id that is currently stored. Different entries may have the
  same rectangle.
- The **distance** from a point `(x, y)` to a rectangle is measured squared:
  `dx*dx + dy*dy`, where `dx = max(x0 - x, 0, x - x1)` and
  `dy = max(y0 - y, 0, y - y1)`. It is 0 when the point lies inside or on the
  rectangle, and it is below `2^41`.

## Structure

- **A height-balanced tree of nodes.** All leaves are at the same depth.
- **Node capacity.** Every node holds at most `M = 16` entries. Every node
  other than the root holds at least `m = 6` entries. The root, if it is a
  leaf, holds 0 to 16 entries (0 only when the tree is empty); if it is an
  internal node, it holds 2 to 16 entries.
- **Leaf entries** are the stored entries, `(rectangle, id)`. Each stored
  entry is in exactly one leaf, once.
- **Internal entries** are `(child, bounding rectangle)`, one per child, where
  the bounding rectangle is **exactly** the bounding rectangle of all the
  entries of that child: not merely a rectangle that contains them. This must
  hold for every internal entry after every operation, so a removal must
  shrink the bounding rectangles above it where it can.
- **Insertion** is Guttman's `Insert`:
  1. *Choose a leaf.* Starting at the root, at each internal node descend
     into the child whose bounding rectangle needs the **least enlargement**
     to include the new rectangle; among equal enlargements, the one with
     the **smallest area**; further ties are your choice.
  2. Add the entry to that leaf. If the leaf now holds 17 entries, **split**
     it into two nodes with the quadratic split below.
  3. *Adjust the tree.* Going back up the path to the root, set each
     internal entry on the path to the exact bounding rectangle of its child,
     and when a child was split, add an entry for the new node to its parent,
     which is split in turn if it now holds 17 entries.
  4. If the root was split, a new root is created with the two halves as its
     children: this is the only way the tree grows taller.
- **Quadratic split** of a node's 17 entries into two nodes:
  1. *PickSeeds.* For every pair of entries `E1`, `E2`, let
     `d = area(J) - area(E1) - area(E2)`, where `J` is the bounding rectangle
     of the two. The pair with the largest `d` starts the two groups, one
     entry in each.
  2. Then, until every entry is assigned: if one group needs all the
     remaining entries to reach `m = 6`, all of them go to that group.
     Otherwise *PickNext*: for every unassigned entry, let `d1` and `d2` be
     the enlargements the bounding rectangles of group 1 and group 2 need to
     include it; take the entry with the largest `|d1 - d2|` and add it to
     the group that needs the smaller enlargement; on a tie, to the group
     with the smaller area, then the one with fewer entries, then either.
  
  Ties between equal values of `d` or of `|d1 - d2|` are your choice. Both
  resulting nodes hold at least 6 entries.
- **Removal** is Guttman's `Delete`:
  1. *Find the leaf* that holds an entry with exactly the given rectangle
     and id, searching every subtree whose bounding rectangle contains the
     rectangle.
  2. Remove the entry from the leaf.
  3. *Condense the tree.* Going up from that leaf to the root: a node other
     than the root that now holds fewer than 6 entries is removed from its
     parent and its remaining entries are set aside; any other node on the
     path gets the exact bounding rectangle of its entries in its parent.
     Then every set-aside entry is inserted again, with the insertion
     algorithm above, at the level it came from: the entries of a leaf as
     leaf entries, and the entries of an internal node as entries of a node
     at that same level, so that all leaves stay at the same depth.
  4. While the root is an internal node with only one child, that child
     becomes the root: this is the only way the tree gets shorter.
- **Nothing else changes the tree.** No bulk loading, no rebuilding, no
  forced reinsertion when a node overflows, no merging or redistributing
  entries between siblings, no deferred or lazy work. A tree's shape is the
  result of exactly these algorithms (and of your choices where ties are left
  open).
- **The R-tree is the only structure that stores entries.** No side index (in
  particular no map from ids or rectangles to leaves: a removal finds its
  entry by searching the tree), no grid or other spatial structure, no cache
  of entries or of query results, no copy of the entries elsewhere.

These invariants must hold after every operation returns.

**Fixed** by this specification: the node capacity (16) and minimum fill
(6, except the root), the invariants above, exact bounding rectangles, the
choice of subtree on insertion, the quadratic split as the only way to split
a node, and removal with condensing and reinsertion.

**Your choice:** how nodes are laid out in memory and where they are
allocated (for example one object per node, arrays of coordinates per node,
or a pool of nodes addressed by index), whether nodes link to their parents,
the order of the entries within a node, how ties left open above are broken,
recursion versus explicit stacks, and how `search` and `nearest` traverse and
prune the tree (for example a best-first search with a priority queue, or a
depth-first branch-and-bound search for `nearest`).

## Operations

| Operation | Behaviour |
| --- | --- |
| `new()` | Create an empty tree. |
| `insert(x0, y0, x1, y1, id)` | Add the entry: the rectangle `(x0, y0, x1, y1)` with `id`. The rectangle is valid and the id is not currently stored. |
| `remove(x0, y0, x1, y1, id) -> bool` | If an entry with exactly this rectangle and this id is stored, remove it and return `true`. Otherwise change nothing and return `false`. |
| `search(x0, y0, x1, y1, out_ids, cap) -> total` | Return `total`, the number of stored entries whose rectangles intersect the query rectangle `(x0, y0, x1, y1)`, and write the ids of `min(total, cap)` of them to `out_ids[0]`, `out_ids[1]`, ..., each id once, in any order. `total` is returned in full even when it is larger than `cap`. `cap` may be 0. |
| `nearest(x, y, k, out_ids) -> count` | Write the ids of the `count = min(k, len())` stored entries nearest to the point `(x, y)` to `out_ids[0 .. count)`, in ascending order of distance and, at equal distance, ascending id, and return `count`. `k` may be 0. |
| `len() -> count` | Number of stored entries. |
| `height() -> levels` | Number of levels of the tree: 0 for an empty tree, 1 when the root is a leaf, and one more for each level of internal nodes above the leaves. |
| `node_count() -> count` | Number of nodes in the tree, leaves and internal nodes. 0 for an empty tree, even if you keep an empty root node allocated. |

Query rectangles obey the same rules as stored rectangles, and the point
of `nearest` has `0 <= x, y < 2^20`. The result of `search` is a set, so its
order is free, and which ids are written when `total > cap` is free. The
result of `nearest` is fully determined: for each `count`, exactly one list
of ids is correct.

Complexity requirements, for a tree of `n` entries:

- `insert`: one path from the root to a leaf, plus the splits along it on
  the way back up (each `O(M^2)`).
- `remove`: searches only subtrees whose bounding rectangles contain the
  rectangle, plus condensing and the reinsertion of the set-aside entries.
- `search`: visits only nodes whose bounding rectangles intersect the query.
- `nearest`: must prune with the distances to the bounding rectangles; it
  must not examine every entry.
- `len`: `O(1)`. `height` and `node_count` may take `O(n)`; they are used
  only to check the tree and are never timed.

A tree that has been emptied by `remove` must be fully usable again.

## Rules

- Write the R-tree yourself. Do not use or wrap a spatial index, tree, or
  ordered or hashed container from a library to hold the entries or the
  nodes (`std::map`, `std::unordered_map`, `BTreeMap`, `HashMap`, `TreeMap`,
  `dict`, ...). Plain growable arrays used as node storage or as pools of
  nodes are fine, and so are a library priority queue, stack, or sort used
  as temporary working storage inside one operation (for example the
  candidate queue of `nearest`).
- Use only the language's standard library. No third-party packages and no
  code in another language (no C extensions, FFI, JNI, cgo, or inline assembly).
- No architecture-specific SIMD intrinsics (`<arm_neon.h>`, `std::arch`,
  `System.Runtime.Intrinsics`, and the like). Portable features of the
  language and its compiler are fine: branch hints, prefetch hints, and
  portable vector types.
- Single-threaded: do not start threads or processes.
- Do not change process-wide runtime settings (garbage collector tuning,
  JIT flags, recursion limits, allocator replacement, and so on).
- Low-level utilities from the standard library are fine: arrays, block
  copies, bit operations, and similar.
- Memory use must stay proportional to the largest number of entries the tree
  has held, and everything is released when the tree is destroyed in
  languages with manual memory management.
- Language features that trade safety for speed (for example `unsafe` in
  Rust) are permitted.

The exact names, signatures, and file names for your language are given in
the language binding that accompanies this specification. The benchmark
driver calls exactly that interface.

## How it is judged

1. **Correctness.** A fixed test suite drives the tree through ten workloads
   at several sizes up to 10,000 entries, and compares every result
   against a reference. Two correct trees may have different shapes, so no
   check depends on the shape; instead `height()` and `node_count()` are
   checked against the bounds every tree that meets the invariants above
   satisfies. For `n >= 1` entries:
   - `height()` is at least the smallest `h >= 1` with `16^h >= n`, and at
     most the largest `h` with `h == 1` or `2 * 6^(h-1) <= n`;
   - `node_count()` is at least `c1 + c2 + ...`, where `c1 = ceil(n / 16)`
     and `c(i+1) = ceil(c(i) / 16)` down to a level of 1 node, and at most
     `1 + floor(n / 6) + floor(n / 36) + floor(n / 216) + ...`.
2. **Speed.** The same ten workloads are then timed on trees of 400,000
   rectangles, far larger than the CPU caches. Only the time spent inside
   your operations is measured, so write for performance: the goal is the
   fastest correct R-tree you can write in this language.
