120 static_assert(MaxEntries >= 2,
"RTree requires MaxEntries >= 2");
121 static_assert(MinEntries >= 1,
"RTree requires MinEntries >= 1");
122 static_assert(2 * MinEntries <= MaxEntries + 1,
"RTree requires 2 * MinEntries <= MaxEntries + 1");
123 static_assert(std::default_initializable<Payload>,
124 "RTree requires default-initializable Payload");
125 static_assert(std::movable<Payload>,
"RTree requires movable Payload");
157 size_t root = std::numeric_limits<size_t>::max();
201 return {xmin, ymin, xmax, ymax};
221 return (xhi - xlo) * (yhi - ylo);
235 for (
size_t i = 1; i < node.
data.size(); ++i)
240 for (
size_t i = 1; i < node.
children.size(); ++i)
256 for (
size_t i = 1; i < node.
children.size(); ++i)
260 if (e < best_enlarge or (e == best_enlarge
and a < best_area))
281 for (
size_t i = 0; i <
k; ++i)
285 for (
size_t j = 0; j <
k; ++j)
291 if (first or ov < best_ov or
292 (ov == best_ov
and (enl < best_enl or (enl == best_enl
and area < best_area))))
309 template <
typename EntryT>
312 const size_t n = entries.
size();
323 union_bbox(items(0).bbox, items(1).bbox).
area() - items(0).bbox.area() - items(1).bbox.area();
324 for (
size_t i = 0; i < n; ++i)
325 for (
size_t j = i + 1; j < n; ++j)
328 items(i).bbox.area() - items(j).bbox.area();
337 std::array<bool, MaxEntries + 1> assigned{};
340 assigned[seed1] =
true;
341 assigned[seed2] =
true;
342 group1.
append(std::move(items(seed1)));
343 group2.append(std::move(items(seed2)));
344 size_t remaining = n - 2;
348 for (
size_t k = 0;
k < n; ++
k)
352 group.append(std::move(items(
k)));
357 while (remaining > 0)
360 if (group1.size() + remaining == MinEntries)
365 if (group2.size() + remaining == MinEntries)
376 for (
size_t k = 0;
k < n; ++
k)
383 if (pick == n or
diff > best_diff)
395 if (pick_d1 < pick_d2)
397 else if (pick_d2 < pick_d1)
399 else if (mbr1.
area() != mbr2.
area())
400 to_group1 = mbr1.
area() < mbr2.
area();
402 to_group1 = group1.size() <= group2.size();
404 assigned[pick] =
true;
408 group1.append(std::move(items(pick)));
413 group2.append(std::move(items(pick)));
418 entries = std::move(group1);
426 template <
typename EntryT>
429 const size_t n = entries.
size();
440 auto make_mbr_cache = [&items, n](
const std::array<size_t, MaxEntries + 1> &order)
442 std::array<Rectangle, MaxEntries + 2>
prefix{};
443 std::array<Rectangle, MaxEntries + 2>
suffix{};
444 prefix[1] = items(order[0]).bbox;
445 for (
size_t k = 2;
k <= n; ++
k)
447 suffix[n - 1] = items(order[n - 1]).bbox;
448 for (
size_t k = n - 1;
k > 0; --
k)
453 auto make_order = [&items, n](
const int axis,
const int edge)
455 std::array<size_t, MaxEntries + 1> order{};
456 for (
size_t i = 0; i < n; ++i)
459 [&items, axis, edge](
const size_t a,
const size_t b)
461 const Rectangle &ra = items(a).bbox;
462 const Rectangle &rb = items(b).bbox;
463 const Geom_Number la = axis == 0 ? ra.get_xmin() : ra.get_ymin();
464 const Geom_Number ua = axis == 0 ? ra.get_xmax() : ra.get_ymax();
465 const Geom_Number lb = axis == 0 ? rb.get_xmin() : rb.get_ymin();
466 const Geom_Number ub = axis == 0 ? rb.get_xmax() : rb.get_ymax();
467 const Geom_Number pa = edge == 0 ? la : ua;
468 const Geom_Number pb = edge == 0 ? lb : ub;
471 return (edge == 0 ? ua : la) < (edge == 0 ? ub : lb);
480 for (
int axis = 0; axis < 2; ++axis)
483 for (
int edge = 0; edge < 2; ++edge)
485 const std::array<size_t, MaxEntries + 1> order = make_order(axis, edge);
487 for (
size_t sz = MinEntries; sz <= n - MinEntries; ++sz)
488 margin_sum +=
prefix[sz].perimeter() +
suffix[sz].perimeter();
490 if (axis == 0 or margin_sum < best_margin_sum)
492 best_margin_sum = margin_sum;
498 std::array<size_t, MaxEntries + 1> best_order{};
499 size_t best_sz = MinEntries;
503 for (
int edge = 0; edge < 2; ++edge)
505 const std::array<size_t, MaxEntries + 1> order = make_order(chosen_axis, edge);
507 for (
size_t sz = MinEntries; sz <= n - MinEntries; ++sz)
513 if (first or ov < best_overlap or (ov == best_overlap
and ar < best_area))
524 for (
size_t k = 0;
k < best_sz; ++
k)
525 group1.append(std::move(items(best_order[
k])));
526 for (
size_t k = best_sz;
k < n; ++
k)
527 group2.append(std::move(items(best_order[
k])));
528 entries = std::move(group1);
535 template <
typename EntryT>
549 const size_t n = node.
data.size();
552 std::array<size_t, MaxEntries + 1> order{};
553 for (
size_t i = 0; i < n; ++i)
555 introsort(order.data(), n, [&node, ¢re](
const size_t a,
const size_t b)
557 return node.data(a).bbox.center().distance_squared_to(centre) >
558 node.data(b).bbox.center().distance_squared_to(centre);
561 size_t p = (3 * MaxEntries) / 10;
564 if (p > MaxEntries + 1 - MinEntries)
565 p = MaxEntries + 1 - MinEntries;
569 for (
size_t k = p;
k < n; ++
k)
570 kept.append(std::move(node.
data(order[
k])));
571 for (
size_t k = 0;
k < p; ++
k)
573 node.
data = std::move(kept);
582 node.
data.reserve(MaxEntries + 1);
583 node.
data.append(std::move(entry));
584 if (node.
data.size() <= MaxEntries)
596 auto sibling = std::make_unique<Node>();
597 sibling->leaf =
true;
598 sibling->data = std::move(group2);
605 if (
split ==
nullptr)
609 node.
children.reserve(MaxEntries + 1);
611 if (node.
children.size() <= MaxEntries)
615 auto sibling = std::make_unique<Node>();
616 sibling->leaf =
false;
617 sibling->children = std::move(group2);
625 if (
root_ ==
nullptr)
627 auto root = std::make_unique<Node>();
629 root->data.reserve(1);
630 root->data.append(std::move(entry));
637 if (
split ==
nullptr)
640 auto new_root = std::make_unique<Node>();
641 new_root->leaf =
false;
642 new_root->children.reserve(2);
645 root_ = std::move(new_root);
673 for (
size_t i = 0; i < node.
data.size(); ++i)
674 out.append(std::move(node.
data(i)));
677 for (
size_t i = 0; i < node.
children.size(); ++i)
684 return node.
data.size();
686 for (
size_t i = 0; i < node.
children.size(); ++i)
690 <<
"RTree: data entry count would overflow";
691 total += subtree_count;
701 requires std::equality_comparable<Payload>
705 for (
size_t i = 0; i < node.data.size(); ++i)
706 if (node.data(i).bbox == bbox
and node.data(i).value ==
value)
709 for (
size_t j = 0; j < node.data.size(); ++j)
711 kept.append(std::move(node.data(j)));
712 node.data = std::move(kept);
719 for (
size_t i = 0; i < node.children.size(); ++i)
721 Child &c = node.children(i);
733 std::numeric_limits<size_t>::max() - orphan_count)
734 <<
"RTree: orphan collection would overflow";
735 orphans.reserve(orphans.size() + orphan_count);
738 for (
size_t j = 0; j < node.children.size(); ++j)
740 kept.append(std::move(node.children(j)));
741 node.children = std::move(kept);
758 template <
typename F>
763 for (
size_t i = 0; i < node.
data.size(); ++i)
764 if (node.
data(i).bbox.intersects(rect))
765 f(node.
data(i).bbox, node.
data(i).value);
768 for (
size_t i = 0; i < node.
children.size(); ++i)
769 if (node.
children(i).bbox.intersects(rect))
773 template <
typename F>
778 for (
size_t i = 0; i < node.
data.size(); ++i)
779 if (node.
data(i).bbox.contains(p))
780 f(node.
data(i).bbox, node.
data(i).value);
783 for (
size_t i = 0; i < node.
children.size(); ++i)
784 if (node.
children(i).bbox.contains(p))
791 requires (std::is_copy_constructible_v<Payload>
and std::movable<Payload>)
793 auto copy = std::make_unique<Node>();
794 copy->leaf = node.leaf;
797 copy->data.reserve(node.data.size());
798 for (
size_t i = 0; i < node.data.size(); ++i)
799 copy->data.append(
Entry{node.data(i).bbox, node.data(i).value});
803 copy->children.reserve(node.children.size());
804 for (
size_t i = 0; i < node.children.size(); ++i)
805 copy->children.append(
Child{node.children(i).bbox, clone_node(*node.children(i).child)});
810 [[nodiscard]]
bool verify_rec(
const Node &node,
const size_t depth,
const bool is_root,
816 if (not is_root
and n < MinEntries)
823 if (leaf_depth == std::numeric_limits<size_t>::max())
825 else if (leaf_depth != depth)
828 if (
count > std::numeric_limits<size_t>::max() - n)
834 if (is_root
and n < 2)
838 for (
size_t i = 0; i < node.
children.size(); ++i)
843 if (node.
children(i).bbox != child_mbr)
845 acc = i == 0 ? child_mbr :
union_bbox(acc, child_mbr);
869 other.clear_rstar_reinsert_state();
884 root_ = std::move(other.root_);
890 other.clear_rstar_reinsert_state();
899 requires (std::is_copy_constructible_v<Payload>
and std::movable<Payload>)
902 if (other.root_ !=
nullptr)
912 requires (std::is_copy_constructible_v<Payload>
and std::movable<Payload>)
916 std::unique_ptr<Node> new_root;
917 if (other.root_ !=
nullptr)
919 root_ = std::move(new_root);
938 [[nodiscard]]
size_t size() const noexcept
947 [[nodiscard]]
size_t height() const noexcept
973 <<
"RTree: size would overflow";
988 <<
"RTree: size would overflow";
1002 requires std::equality_comparable<Payload>
1004 if (
root_ ==
nullptr)
1008 bool removed =
false;
1017 for (
size_t i = 0; i < orphans.
size(); ++i)
1042 template <
typename F>
1045 if (
root_ !=
nullptr)
1055 requires (std::is_copy_constructible_v<Payload>
and std::movable<Payload>)
1060 out.append(Payload(v));
1071 requires (std::is_copy_constructible_v<Payload>
and std::movable<Payload>)
1074 auto collect = [&
out](
const Rectangle &,
const Payload &v)
1078 if (
root_ !=
nullptr)
1094 if (
root_ ==
nullptr)
1097 size_t leaf_depth = std::numeric_limits<size_t>::max();
1118 if (
root_ ==
nullptr)
1124 auto dfs = [&](
const auto &self,
const Node &node,
const size_t depth) ->
size_t
1126 const size_t out_idx = snap.
nodes.size();
1128 snap.
nodes(out_idx).is_leaf = node.leaf;
1129 snap.
nodes(out_idx).depth = depth;
1137 boxes.
reserve(node.data.size());
1138 for (
size_t i = 0; i < node.data.size(); ++i)
1139 boxes.
append(node.data(i).bbox);
1143 snap.
nodes(out_idx).children.reserve(node.children.size());
1144 for (
size_t i = 0; i < node.children.size(); ++i)
1146 const size_t child_idx = self(self, *node.children(i).child, depth + 1);
1147 snap.
nodes(out_idx).children.append(child_idx);
Exception handling system with formatted messages for Aleph-w.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
size_t size_t int32_t value
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
static Array create_reserved(const size_t cap)
Build an empty array with room for at least cap items.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
Represents a point with rectangular coordinates in a 2D plane.
Dynamic R-tree indexing axis-aligned rectangles by payload.
size_t height_
Number of node levels (0 when empty).
static Array< EntryT > quadratic_split(Array< EntryT > &entries)
Split an overflowed entry array in two using the quadratic heuristic.
static size_t rstar_choose_overlap(const Node &node, const Rectangle &bbox)
R*-tree ChooseSubtree for a node whose children are leaves: pick the child whose growth adds the leas...
void for_each_intersecting_rec(const Node &node, const Rectangle &rect, F &f) const
static Array< EntryT > split_entries(Array< EntryT > &entries)
Split the entry array of node according to the active variant.
static Rectangle union_bbox(const Rectangle &a, const Rectangle &b)
static Geom_Number enlargement(const Rectangle &base, const Rectangle &added)
Area added to base by growing it to also cover added.
void reinsert_farthest(Node &node)
Move the R*-tree forced-reinsert candidates (the entries farthest from the node centre) out of the ov...
void add_entry(Entry entry)
Add a data entry without touching size_ (shared by insert and by erase-time reinsertion).
static size_t entry_count(const Node &node)
void clear_rstar_reinsert_state() noexcept
Drop R*-tree transient insertion state.
static Geom_Number overlap_area(const Rectangle &a, const Rectangle &b)
Area of the overlap between two rectangles (0 if disjoint).
DebugSnapshot debug_snapshot() const
Capture the full tree structure for visualization/debugging.
void insert_one(Entry entry)
Insert one data entry into the tree (no size_ change, no reinsert-buffer management).
void insert(const Rectangle &bbox, const Payload &value)
Insert a (bbox, value) entry, copying value.
RTree(const RTree &other)
Deep-copy other (requires copy-constructible, movable Payload).
static size_t data_entry_count(const Node &node)
static bool box_contains_box(const Rectangle &outer, const Rectangle &inner)
True iff outer fully covers inner.
bool erase(const Rectangle &bbox, const Payload &value)
Remove one entry equal to (bbox, value).
static Rectangle compute_mbr(const Node &node)
Tight bounding box covering every entry of node.
static size_t choose_subtree(const Node &node, const Rectangle &bbox)
Choose the child of node into which bbox should be inserted.
void erase_descend(Node &node, const Rectangle &bbox, const Payload &value, Array< Entry > &orphans, bool &removed)
Remove one entry equal to (bbox, value) from node's subtree.
size_t height() const noexcept
Return the number of node levels (0 when empty, 1 for a lone leaf).
RTree() noexcept=default
Construct an empty R-tree.
bool rstar_reinsert_available_
Leaf-level reinsert not yet used this insert.
bool is_empty() const noexcept
Return true when the tree has no entries.
void insert(const Rectangle &bbox, Payload &&value)
Insert a (bbox, value) entry, moving value.
Array< Payload > search_intersects(const Rectangle &rect) const
Return the payloads of every entry whose bbox intersects rect.
void for_each_containing_rec(const Node &node, const Point &p, F &f) const
Array< Payload > search_contains(const Point &p) const
Return the payloads of every entry whose bbox contains p.
size_t size() const noexcept
Return the number of stored entries.
std::unique_ptr< Node > insert_descend(Node &node, Entry entry)
Insert entry at the leaf level of node.
RTree & operator=(RTree &&other) noexcept
Move-assign from other, leaving it empty and valid.
void for_each_intersecting(const Rectangle &rect, F &&f) const
Invoke f for every entry whose bbox intersects rect.
static Array< EntryT > rstar_split(Array< EntryT > &entries)
R*-tree split: choose the split axis minimizing the total margin of the two groups,...
bool verify_rec(const Node &node, const size_t depth, const bool is_root, size_t &leaf_depth, size_t &count, Rectangle &out_mbr) const
std::unique_ptr< Node > root_
static std::unique_ptr< Node > clone_node(const Node &node)
bool verify() const
Verify the R-tree structural invariants.
void clear() noexcept
Remove all entries.
size_t size_
Number of stored data entries.
Array< Entry > rstar_reinsert_buffer_
Entries pending forced reinsertion.
static void collect_data_entries(Node &node, Array< Entry > &out)
Move every data entry in node's subtree into out.
An axis-aligned rectangle.
const Geom_Number & get_xmin() const
Gets the minimum x-coordinate.
const Geom_Number & get_ymax() const
Gets the maximum y-coordinate.
const Geom_Number & get_ymin() const
Gets the minimum y-coordinate.
const Geom_Number & get_xmax() const
Gets the maximum x-coordinate.
Point center() const
Calculates the center point of the rectangle.
Geom_Number area() const
Calculates the area of the rectangle.
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Main namespace for Aleph-w library functions.
static void suffix(Node *root, DynList< Node * > &acc)
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
static void prefix(Node *root, DynList< Node * > &acc)
and
Check uniqueness with explicit hash + equality functors.
bool diff(const C1 &c1, const C2 &c2, Eq e=Eq())
Check if two containers differ.
mpq_class Geom_Number
Numeric type used by the geometry module.
std::vector< std::string > & split(const std::string &s, const char delim, std::vector< std::string > &elems)
Split a std::string by a single delimiter character.
void introsort(T *a, const long l, const long r, const Compare &cmp=Compare())
Sort an array using introsort (introspective sort).
RTreeVariant
Node-split / insertion strategy for RTree.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
2D point and geometric utilities.
Internal-node entry: a child subtree plus its tight bounding box.
std::unique_ptr< Node > child
Owned child subtree.
Rectangle bbox
Tight MBR of child.
One node of a debug_snapshot, independent of Payload.
size_t depth
Root is 0, increasing towards the leaves.
bool is_leaf
True for leaf nodes (see entry_boxes).
Array< Rectangle > entry_boxes
Data-entry boxes stored here (leaves only).
Rectangle bbox
Tight MBR of this node.
Array< size_t > children
Indices into DebugSnapshot::nodes (internal nodes).
Full tree structure captured for visualization/debugging.
Array< DebugNode > nodes
Every node, in preorder.
size_t root
Index of the root in nodes.
A stored (bounding box, payload) pair.
Rectangle bbox
Axis-aligned bounding box.
Payload value
User payload associated with bbox.
A node is a leaf holding data or an internal node holding children.
Array< Child > children
Child entries (used iff not leaf).
Array< Entry > data
Data entries (used iff leaf).
Dynamic array container with automatic resizing.
Comprehensive sorting algorithms and search utilities for Aleph-w.