Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_r_tree.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 https://github.com/lrleon/Aleph-w
6
7 This file is part of Aleph-w library
8
9 Copyright (c) 2002-2026 Leandro Rabindranath Leon
10
11 Permission is hereby granted, free of charge, to any person obtaining a copy
12 of this software and associated documentation files (the "Software"), to deal
13 in the Software without restriction, including without limitation the rights
14 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 copies of the Software, and to permit persons to whom the Software is
16 furnished to do so, subject to the following conditions:
17
18 The above copyright notice and this permission notice shall be included in all
19 copies or substantial portions of the Software.
20
21 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 SOFTWARE.
28*/
29
74#ifndef TPL_R_TREE_H
75#define TPL_R_TREE_H
76
77#include <algorithm>
78#include <array>
79#include <concepts>
80#include <cstddef>
81#include <limits>
82#include <memory>
83#include <type_traits>
84#include <utility>
85
86#include <ah-errors.H>
87#include <point.H>
88#include <tpl_array.H>
89#include <tpl_sort_utils.H>
90
91namespace Aleph {
92
99enum class RTreeVariant
100{
101 Guttman,
102 RStar
103};
104
117template <typename Payload, size_t MaxEntries = 16, size_t MinEntries = MaxEntries / 2, RTreeVariant Variant = RTreeVariant::Guttman>
118class RTree
119{
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");
126
127public:
129 struct Entry
130 {
132 Payload value;
133 };
134
149
155 {
157 size_t root = std::numeric_limits<size_t>::max();
158 };
159
160private:
161 struct Node;
162
164 struct Child
165 {
167 std::unique_ptr<Node> child;
168 };
169
177
178 std::unique_ptr<Node> root_;
179 size_t size_ = 0;
180 size_t height_ = 0;
181
182 // R*-only transient state (empty/false while no insertion is in progress).
185
188 {
191 }
192
193 // ---- geometry helpers -------------------------------------------------
194
195 [[nodiscard]] static Rectangle union_bbox(const Rectangle &a, const Rectangle &b)
196 {
197 const Geom_Number xmin = a.get_xmin() < b.get_xmin() ? a.get_xmin() : b.get_xmin();
198 const Geom_Number ymin = a.get_ymin() < b.get_ymin() ? a.get_ymin() : b.get_ymin();
199 const Geom_Number xmax = a.get_xmax() > b.get_xmax() ? a.get_xmax() : b.get_xmax();
200 const Geom_Number ymax = a.get_ymax() > b.get_ymax() ? a.get_ymax() : b.get_ymax();
201 return {xmin, ymin, xmax, ymax};
202 }
203
205 [[nodiscard]] static Geom_Number enlargement(const Rectangle &base, const Rectangle &added)
206 {
207 return union_bbox(base, added).area() - base.area();
208 }
209
211 [[nodiscard]] static Geom_Number overlap_area(const Rectangle &a, const Rectangle &b)
212 {
213 const Geom_Number xlo = a.get_xmin() > b.get_xmin() ? a.get_xmin() : b.get_xmin();
214 const Geom_Number xhi = a.get_xmax() < b.get_xmax() ? a.get_xmax() : b.get_xmax();
215 if (xhi <= xlo)
216 return Geom_Number(0);
217 const Geom_Number ylo = a.get_ymin() > b.get_ymin() ? a.get_ymin() : b.get_ymin();
218 const Geom_Number yhi = a.get_ymax() < b.get_ymax() ? a.get_ymax() : b.get_ymax();
219 if (yhi <= ylo)
220 return Geom_Number(0);
221 return (xhi - xlo) * (yhi - ylo);
222 }
223
224 [[nodiscard]] static size_t entry_count(const Node &node)
225 {
226 return node.leaf ? node.data.size() : node.children.size();
227 }
228
230 [[nodiscard]] static Rectangle compute_mbr(const Node &node)
231 {
232 if (node.leaf)
233 {
234 Rectangle acc = node.data(0).bbox;
235 for (size_t i = 1; i < node.data.size(); ++i)
236 acc = union_bbox(acc, node.data(i).bbox);
237 return acc;
238 }
239 Rectangle acc = node.children(0).bbox;
240 for (size_t i = 1; i < node.children.size(); ++i)
241 acc = union_bbox(acc, node.children(i).bbox);
242 return acc;
243 }
244
247 [[nodiscard]] static size_t choose_subtree(const Node &node, const Rectangle &bbox)
248 {
249 if constexpr (Variant == RTreeVariant::RStar)
250 if (node.children(0).child->leaf)
251 return rstar_choose_overlap(node, bbox);
252
253 size_t best = 0;
254 Geom_Number best_enlarge = enlargement(node.children(0).bbox, bbox);
255 Geom_Number best_area = node.children(0).bbox.area();
256 for (size_t i = 1; i < node.children.size(); ++i)
257 {
258 const Geom_Number e = enlargement(node.children(i).bbox, bbox);
259 const Geom_Number a = node.children(i).bbox.area();
260 if (e < best_enlarge or (e == best_enlarge and a < best_area))
261 {
262 best = i;
263 best_enlarge = e;
264 best_area = a;
265 }
266 }
267 return best;
268 }
269
273 [[nodiscard]] static size_t rstar_choose_overlap(const Node &node, const Rectangle &bbox)
274 {
275 const size_t k = node.children.size();
276 size_t best = 0;
277 bool first = true;
278 Geom_Number best_ov = 0;
279 Geom_Number best_enl = 0;
280 Geom_Number best_area = 0;
281 for (size_t i = 0; i < k; ++i)
282 {
283 const Rectangle grown = union_bbox(node.children(i).bbox, bbox);
284 Geom_Number ov = 0;
285 for (size_t j = 0; j < k; ++j)
286 if (j != i)
287 ov += overlap_area(grown, node.children(j).bbox) -
288 overlap_area(node.children(i).bbox, node.children(j).bbox);
289 const Geom_Number enl = grown.area() - node.children(i).bbox.area();
290 const Geom_Number area = node.children(i).bbox.area();
291 if (first or ov < best_ov or
292 (ov == best_ov and (enl < best_enl or (enl == best_enl and area < best_area))))
293 {
294 best = i;
295 best_ov = ov;
296 best_enl = enl;
297 best_area = area;
298 first = false;
299 }
300 }
301 return best;
302 }
303
304 // ---- quadratic split (Guttman) ----------------------------------------
305
309 template <typename EntryT>
310 [[nodiscard]] static Array<EntryT> quadratic_split(Array<EntryT> &entries)
311 {
312 const size_t n = entries.size();
313 auto group1 = Array<EntryT>::create_reserved(n);
314 auto group2 = Array<EntryT>::create_reserved(n);
315
316 Array<EntryT> items = std::move(entries);
317 entries = Array<EntryT>();
318
319 // PickSeeds: the pair wasting the most area if grouped together.
320 size_t seed1 = 0;
321 size_t seed2 = 1;
322 Geom_Number worst =
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)
326 {
327 const Geom_Number d = union_bbox(items(i).bbox, items(j).bbox).area() -
328 items(i).bbox.area() - items(j).bbox.area();
329 if (d > worst)
330 {
331 worst = d;
332 seed1 = i;
333 seed2 = j;
334 }
335 }
336
337 std::array<bool, MaxEntries + 1> assigned{};
338 Rectangle mbr1 = items(seed1).bbox;
339 Rectangle mbr2 = items(seed2).bbox;
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;
345
346 auto dump_into = [&](Array<EntryT> &group)
347 {
348 for (size_t k = 0; k < n; ++k)
349 if (not assigned[k])
350 {
351 assigned[k] = true;
352 group.append(std::move(items(k)));
353 }
354 remaining = 0;
355 };
356
357 while (remaining > 0)
358 {
359 // Force the rest into a group that would otherwise miss MinEntries.
360 if (group1.size() + remaining == MinEntries)
361 {
362 dump_into(group1);
363 break;
364 }
365 if (group2.size() + remaining == MinEntries)
366 {
367 dump_into(group2);
368 break;
369 }
370
371 // PickNext: entry with the strongest preference for one group.
372 size_t pick = n;
373 Geom_Number best_diff = 0;
374 Geom_Number pick_d1 = 0;
375 Geom_Number pick_d2 = 0;
376 for (size_t k = 0; k < n; ++k)
377 {
378 if (assigned[k])
379 continue;
380 const Geom_Number d1 = enlargement(mbr1, items(k).bbox);
381 const Geom_Number d2 = enlargement(mbr2, items(k).bbox);
382 const Geom_Number diff = d1 > d2 ? d1 - d2 : d2 - d1;
383 if (pick == n or diff > best_diff)
384 {
385 best_diff = diff;
386 pick = k;
387 pick_d1 = d1;
388 pick_d2 = d2;
389 }
390 }
391
392 // Assign to the group needing less enlargement (ties: smaller area,
393 // then fewer entries).
394 bool to_group1;
395 if (pick_d1 < pick_d2)
396 to_group1 = true;
397 else if (pick_d2 < pick_d1)
398 to_group1 = false;
399 else if (mbr1.area() != mbr2.area())
400 to_group1 = mbr1.area() < mbr2.area();
401 else
402 to_group1 = group1.size() <= group2.size();
403
404 assigned[pick] = true;
405 if (to_group1)
406 {
407 mbr1 = union_bbox(mbr1, items(pick).bbox);
408 group1.append(std::move(items(pick)));
409 }
410 else
411 {
412 mbr2 = union_bbox(mbr2, items(pick).bbox);
413 group2.append(std::move(items(pick)));
414 }
415 --remaining;
416 }
417
418 entries = std::move(group1);
419 return group2;
420 }
421
426 template <typename EntryT>
427 [[nodiscard]] static Array<EntryT> rstar_split(Array<EntryT> &entries)
428 {
429 const size_t n = entries.size();
430 auto group1 = Array<EntryT>::create_reserved(n);
431 auto group2 = Array<EntryT>::create_reserved(n);
432
433 Array<EntryT> items = std::move(entries);
434 entries = Array<EntryT>();
435
436 // prefix/suffix are indexed up to and including n (prefix[n], suffix
437 // accessed down to suffix[0]), and n can reach MaxEntries + 1, so both
438 // need MaxEntries + 2 slots -- one more than the MaxEntries + 1 used for
439 // per-entry arrays like `order`.
440 auto make_mbr_cache = [&items, n](const std::array<size_t, MaxEntries + 1> &order)
441 {
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)
446 prefix[k] = union_bbox(prefix[k - 1], items(order[k - 1]).bbox);
447 suffix[n - 1] = items(order[n - 1]).bbox;
448 for (size_t k = n - 1; k > 0; --k)
449 suffix[k - 1] = union_bbox(items(order[k - 1]).bbox, suffix[k]);
450 return std::pair{prefix, suffix};
451 };
452
453 auto make_order = [&items, n](const int axis, const int edge)
454 {
455 std::array<size_t, MaxEntries + 1> order{};
456 for (size_t i = 0; i < n; ++i)
457 order[i] = i;
458 introsort(order.data(), n,
459 [&items, axis, edge](const size_t a, const size_t b)
460 {
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;
469 if (pa != pb)
470 return pa < pb;
471 return (edge == 0 ? ua : la) < (edge == 0 ? ub : lb);
472 });
473 return order;
474 };
475
476 // ChooseSplitAxis: minimize the summed margin over both edge sortings and
477 // all valid distributions.
478 int chosen_axis = 0;
479 Geom_Number best_margin_sum = 0;
480 for (int axis = 0; axis < 2; ++axis)
481 {
482 Geom_Number margin_sum = 0;
483 for (int edge = 0; edge < 2; ++edge)
484 {
485 const std::array<size_t, MaxEntries + 1> order = make_order(axis, edge);
486 const auto [prefix, suffix] = make_mbr_cache(order);
487 for (size_t sz = MinEntries; sz <= n - MinEntries; ++sz)
488 margin_sum += prefix[sz].perimeter() + suffix[sz].perimeter();
489 }
490 if (axis == 0 or margin_sum < best_margin_sum)
491 {
492 best_margin_sum = margin_sum;
493 chosen_axis = axis;
494 }
495 }
496
497 // ChooseSplitIndex: on the chosen axis, minimize overlap area, then area.
498 std::array<size_t, MaxEntries + 1> best_order{};
499 size_t best_sz = MinEntries;
500 bool first = true;
501 Geom_Number best_overlap = 0;
502 Geom_Number best_area = 0;
503 for (int edge = 0; edge < 2; ++edge)
504 {
505 const std::array<size_t, MaxEntries + 1> order = make_order(chosen_axis, edge);
506 const auto [prefix, suffix] = make_mbr_cache(order);
507 for (size_t sz = MinEntries; sz <= n - MinEntries; ++sz)
508 {
509 const Rectangle &g1 = prefix[sz];
510 const Rectangle &g2 = suffix[sz];
511 const Geom_Number ov = overlap_area(g1, g2);
512 const Geom_Number ar = g1.area() + g2.area();
513 if (first or ov < best_overlap or (ov == best_overlap and ar < best_area))
514 {
515 first = false;
516 best_overlap = ov;
517 best_area = ar;
518 best_order = order;
519 best_sz = sz;
520 }
521 }
522 }
523
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);
529 return group2;
530 }
531
532 // ---- insertion --------------------------------------------------------
533
535 template <typename EntryT>
536 [[nodiscard]] static Array<EntryT> split_entries(Array<EntryT> &entries)
537 {
538 if constexpr (Variant == RTreeVariant::RStar)
539 return rstar_split(entries);
540 else
541 return quadratic_split(entries);
542 }
543
548 {
549 const size_t n = node.data.size();
550 const Point centre = compute_mbr(node).center();
551
552 std::array<size_t, MaxEntries + 1> order{};
553 for (size_t i = 0; i < n; ++i)
554 order[i] = i;
555 introsort(order.data(), n, [&node, &centre](const size_t a, const size_t b)
556 {
557 return node.data(a).bbox.center().distance_squared_to(centre) >
558 node.data(b).bbox.center().distance_squared_to(centre);
559 });
560
561 size_t p = (3 * MaxEntries) / 10;
562 if (p < 1)
563 p = 1;
564 if (p > MaxEntries + 1 - MinEntries)
565 p = MaxEntries + 1 - MinEntries;
566
567 auto kept = Array<Entry>::create_reserved(n - p);
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)
572 rstar_reinsert_buffer_.append(std::move(node.data(order[k])));
573 node.data = std::move(kept);
574 }
575
578 [[nodiscard]] std::unique_ptr<Node> insert_descend(Node &node, Entry entry)
579 {
580 if (node.leaf)
581 {
582 node.data.reserve(MaxEntries + 1);
583 node.data.append(std::move(entry));
584 if (node.data.size() <= MaxEntries)
585 return nullptr;
586
587 if constexpr (Variant == RTreeVariant::RStar)
588 if (rstar_reinsert_available_ and &node != root_.get())
589 {
591 reinsert_farthest(node);
592 return nullptr;
593 }
594
595 Array<Entry> group2 = split_entries(node.data);
596 auto sibling = std::make_unique<Node>();
597 sibling->leaf = true;
598 sibling->data = std::move(group2);
599 return sibling;
600 }
601
602 const size_t idx = choose_subtree(node, entry.bbox);
603 std::unique_ptr<Node> split = insert_descend(*node.children(idx).child, std::move(entry));
604 node.children(idx).bbox = compute_mbr(*node.children(idx).child);
605 if (split == nullptr)
606 return nullptr;
607
608 Rectangle split_mbr = compute_mbr(*split);
609 node.children.reserve(MaxEntries + 1);
610 node.children.append(Child{std::move(split_mbr), std::move(split)});
611 if (node.children.size() <= MaxEntries)
612 return nullptr;
613
614 Array<Child> group2 = split_entries(node.children);
615 auto sibling = std::make_unique<Node>();
616 sibling->leaf = false;
617 sibling->children = std::move(group2);
618 return sibling;
619 }
620
623 void insert_one(Entry entry)
624 {
625 if (root_ == nullptr)
626 {
627 auto root = std::make_unique<Node>();
628 root->leaf = true;
629 root->data.reserve(1);
630 root->data.append(std::move(entry));
631 root_ = std::move(root);
632 height_ = 1;
633 return;
634 }
635
636 std::unique_ptr<Node> split = insert_descend(*root_, std::move(entry));
637 if (split == nullptr)
638 return;
639
640 auto new_root = std::make_unique<Node>();
641 new_root->leaf = false;
642 new_root->children.reserve(2);
643 new_root->children.append(Child{compute_mbr(*root_), std::move(root_)});
644 new_root->children.append(Child{compute_mbr(*split), std::move(split)});
645 root_ = std::move(new_root);
646 ++height_;
647 }
648
652 void add_entry(Entry entry)
653 {
654 if constexpr (Variant == RTreeVariant::RStar)
655 {
657 insert_one(std::move(entry));
658 while (not rstar_reinsert_buffer_.is_empty())
659 insert_one(rstar_reinsert_buffer_.remove_last());
661 }
662 else
663 insert_one(std::move(entry));
664 }
665
666 // ---- deletion ---------------------------------------------------------
667
670 {
671 if (node.leaf)
672 {
673 for (size_t i = 0; i < node.data.size(); ++i)
674 out.append(std::move(node.data(i)));
675 return;
676 }
677 for (size_t i = 0; i < node.children.size(); ++i)
678 collect_data_entries(*node.children(i).child, out);
679 }
680
681 [[nodiscard]] static size_t data_entry_count(const Node &node)
682 {
683 if (node.leaf)
684 return node.data.size();
685 size_t total = 0;
686 for (size_t i = 0; i < node.children.size(); ++i)
687 {
688 const size_t subtree_count = data_entry_count(*node.children(i).child);
689 ah_overflow_error_if(total > std::numeric_limits<size_t>::max() - subtree_count)
690 << "RTree: data entry count would overflow";
691 total += subtree_count;
692 }
693 return total;
694 }
695
699 void erase_descend(Node &node, const Rectangle &bbox, const Payload &value, Array<Entry> &orphans,
700 bool &removed)
701 requires std::equality_comparable<Payload>
702 {
703 if (node.leaf)
704 {
705 for (size_t i = 0; i < node.data.size(); ++i)
706 if (node.data(i).bbox == bbox and node.data(i).value == value)
707 {
708 auto kept = Array<Entry>::create_reserved(node.data.size() - 1);
709 for (size_t j = 0; j < node.data.size(); ++j)
710 if (j != i)
711 kept.append(std::move(node.data(j)));
712 node.data = std::move(kept);
713 removed = true;
714 return;
715 }
716 return;
717 }
718
719 for (size_t i = 0; i < node.children.size(); ++i)
720 {
721 Child &c = node.children(i);
722 if (not box_contains_box(c.bbox, bbox))
723 continue;
724
725 erase_descend(*c.child, bbox, value, orphans, removed);
726 if (not removed)
727 continue;
728
729 if (entry_count(*c.child) < MinEntries)
730 {
731 const size_t orphan_count = data_entry_count(*c.child);
732 ah_overflow_error_if(orphans.size() >
733 std::numeric_limits<size_t>::max() - orphan_count)
734 << "RTree: orphan collection would overflow";
735 orphans.reserve(orphans.size() + orphan_count);
736 auto kept = Array<Child>::create_reserved(node.children.size() - 1);
737 collect_data_entries(*c.child, orphans);
738 for (size_t j = 0; j < node.children.size(); ++j)
739 if (j != i)
740 kept.append(std::move(node.children(j)));
741 node.children = std::move(kept);
742 }
743 else
744 c.bbox = compute_mbr(*c.child);
745 return;
746 }
747 }
748
750 [[nodiscard]] static bool box_contains_box(const Rectangle &outer, const Rectangle &inner)
751 {
752 return outer.get_xmin() <= inner.get_xmin() and outer.get_xmax() >= inner.get_xmax() and
753 outer.get_ymin() <= inner.get_ymin() and outer.get_ymax() >= inner.get_ymax();
754 }
755
756 // ---- queries ----------------------------------------------------------
757
758 template <typename F>
759 void for_each_intersecting_rec(const Node &node, const Rectangle &rect, F &f) const
760 {
761 if (node.leaf)
762 {
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);
766 return;
767 }
768 for (size_t i = 0; i < node.children.size(); ++i)
769 if (node.children(i).bbox.intersects(rect))
770 for_each_intersecting_rec(*node.children(i).child, rect, f);
771 }
772
773 template <typename F>
774 void for_each_containing_rec(const Node &node, const Point &p, F &f) const
775 {
776 if (node.leaf)
777 {
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);
781 return;
782 }
783 for (size_t i = 0; i < node.children.size(); ++i)
784 if (node.children(i).bbox.contains(p))
785 for_each_containing_rec(*node.children(i).child, p, f);
786 }
787
788 // ---- copy / verify ----------------------------------------------------
789
790 [[nodiscard]] static std::unique_ptr<Node> clone_node(const Node &node)
791 requires (std::is_copy_constructible_v<Payload> and std::movable<Payload>)
792 {
793 auto copy = std::make_unique<Node>();
794 copy->leaf = node.leaf;
795 if (node.leaf)
796 {
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});
800 }
801 else
802 {
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)});
806 }
807 return copy;
808 }
809
810 [[nodiscard]] bool verify_rec(const Node &node, const size_t depth, const bool is_root,
811 size_t &leaf_depth, size_t &count, Rectangle &out_mbr) const
812 {
813 const size_t n = entry_count(node);
814 if (n > MaxEntries)
815 return false;
816 if (not is_root and n < MinEntries)
817 return false;
818 if (n == 0)
819 return false; // an empty node must never be retained
820
821 if (node.leaf)
822 {
823 if (leaf_depth == std::numeric_limits<size_t>::max())
824 leaf_depth = depth;
825 else if (leaf_depth != depth)
826 return false;
827 out_mbr = compute_mbr(node);
828 if (count > std::numeric_limits<size_t>::max() - n)
829 return false;
830 count += n;
831 return true;
832 }
833
834 if (is_root and n < 2)
835 return false; // a non-leaf root must have at least two children
836
837 Rectangle acc;
838 for (size_t i = 0; i < node.children.size(); ++i)
839 {
840 Rectangle child_mbr;
841 if (not verify_rec(*node.children(i).child, depth + 1, false, leaf_depth, count, child_mbr))
842 return false;
843 if (node.children(i).bbox != child_mbr)
844 return false; // stored MBR must be tight
845 acc = i == 0 ? child_mbr : union_bbox(acc, child_mbr);
846 }
847 out_mbr = acc;
848 return true;
849 }
850
851public:
855 RTree() noexcept = default;
856
864 RTree(RTree &&other) noexcept
865 : root_(std::move(other.root_)), size_(other.size_), height_(other.height_)
866 {
867 other.size_ = 0;
868 other.height_ = 0;
869 other.clear_rstar_reinsert_state();
870 }
871
880 RTree &operator = (RTree &&other) noexcept
881 {
882 if (this == &other)
883 return *this;
884 root_ = std::move(other.root_);
885 size_ = other.size_;
886 height_ = other.height_;
888 other.size_ = 0;
889 other.height_ = 0;
890 other.clear_rstar_reinsert_state();
891 return *this;
892 }
893
898 RTree(const RTree &other)
899 requires (std::is_copy_constructible_v<Payload> and std::movable<Payload>)
900 : size_(other.size_), height_(other.height_)
901 {
902 if (other.root_ != nullptr)
903 root_ = clone_node(*other.root_);
904 }
905
911 RTree &operator = (const RTree &other)
912 requires (std::is_copy_constructible_v<Payload> and std::movable<Payload>)
913 {
914 if (this == &other)
915 return *this;
916 std::unique_ptr<Node> new_root;
917 if (other.root_ != nullptr)
918 new_root = clone_node(*other.root_);
919 root_ = std::move(new_root);
920 size_ = other.size_;
921 height_ = other.height_;
922 return *this;
923 }
924
929 [[nodiscard]] bool is_empty() const noexcept
930 {
931 return size_ == 0;
932 }
933
938 [[nodiscard]] size_t size() const noexcept
939 {
940 return size_;
941 }
942
947 [[nodiscard]] size_t height() const noexcept
948 {
949 return height_;
950 }
951
955 void clear() noexcept
956 {
957 root_.reset();
958 size_ = 0;
959 height_ = 0;
961 }
962
970 void insert(const Rectangle &bbox, const Payload &value)
971 {
972 ah_overflow_error_if(size_ == std::numeric_limits<size_t>::max())
973 << "RTree: size would overflow";
974 add_entry(Entry{bbox, value});
975 ++size_;
976 }
977
985 void insert(const Rectangle &bbox, Payload &&value)
986 {
987 ah_overflow_error_if(size_ == std::numeric_limits<size_t>::max())
988 << "RTree: size would overflow";
989 add_entry(Entry{bbox, std::move(value)});
990 ++size_;
991 }
992
1001 [[nodiscard]] bool erase(const Rectangle &bbox, const Payload &value)
1002 requires std::equality_comparable<Payload>
1003 {
1004 if (root_ == nullptr)
1005 return false;
1006
1007 Array<Entry> orphans;
1008 bool removed = false;
1009 erase_descend(*root_, bbox, value, orphans, removed);
1010 if (not removed)
1011 return false;
1012
1013 --size_;
1014
1015 // Reinsert the entries orphaned by condensing (they remain in the tree, so
1016 // add_entry must not change size_).
1017 for (size_t i = 0; i < orphans.size(); ++i)
1018 add_entry(std::move(orphans(i)));
1019
1020 // Shrink a non-leaf root that ended up with a single child.
1021 while (root_ != nullptr and not root_->leaf and root_->children.size() == 1)
1022 {
1023 root_ = std::move(root_->children(0).child);
1024 --height_;
1025 }
1026 // Drop an emptied leaf root.
1027 if (root_ != nullptr and root_->leaf and root_->data.is_empty())
1028 {
1029 root_.reset();
1030 height_ = 0;
1031 }
1032 return true;
1033 }
1034
1042 template <typename F>
1043 void for_each_intersecting(const Rectangle &rect, F &&f) const
1044 {
1045 if (root_ != nullptr)
1047 }
1048
1054 [[nodiscard]] Array<Payload> search_intersects(const Rectangle &rect) const
1055 requires (std::is_copy_constructible_v<Payload> and std::movable<Payload>)
1056 {
1058 for_each_intersecting(rect, [&out](const Rectangle &, const Payload &v)
1059 {
1060 out.append(Payload(v));
1061 });
1062 return out;
1063 }
1064
1070 [[nodiscard]] Array<Payload> search_contains(const Point &p) const
1071 requires (std::is_copy_constructible_v<Payload> and std::movable<Payload>)
1072 {
1074 auto collect = [&out](const Rectangle &, const Payload &v)
1075 {
1076 out.append(Payload(v));
1077 };
1078 if (root_ != nullptr)
1079 for_each_containing_rec(*root_, p, collect);
1080 return out;
1081 }
1082
1092 [[nodiscard]] bool verify() const
1093 {
1094 if (root_ == nullptr)
1095 return size_ == 0 and height_ == 0;
1096
1097 size_t leaf_depth = std::numeric_limits<size_t>::max();
1098 size_t count = 0;
1099 Rectangle mbr;
1100 if (not verify_rec(*root_, 1, true, leaf_depth, count, mbr))
1101 return false;
1102 return count == size_ and leaf_depth == height_;
1103 }
1104
1115 [[nodiscard]] DebugSnapshot debug_snapshot() const
1116 {
1117 DebugSnapshot snap;
1118 if (root_ == nullptr)
1119 return snap;
1120
1121 // Each `snap.nodes(out_idx)` access below is by index, re-fetched after
1122 // every recursive call: `Array::append` may reallocate the backing
1123 // storage, so a reference taken before recursing could dangle.
1124 auto dfs = [&](const auto &self, const Node &node, const size_t depth) -> size_t
1125 {
1126 const size_t out_idx = snap.nodes.size();
1127 snap.nodes.append(DebugNode{});
1128 snap.nodes(out_idx).is_leaf = node.leaf;
1129 snap.nodes(out_idx).depth = depth;
1130
1131 if (node.leaf)
1132 {
1133 // Safe to populate in place: this loop does not recurse, so
1134 // `snap.nodes` cannot reallocate between the reference below
1135 // and its last use.
1136 Array<Rectangle> &boxes = snap.nodes(out_idx).entry_boxes;
1137 boxes.reserve(node.data.size());
1138 for (size_t i = 0; i < node.data.size(); ++i)
1139 boxes.append(node.data(i).bbox);
1140 }
1141 else
1142 {
1143 snap.nodes(out_idx).children.reserve(node.children.size());
1144 for (size_t i = 0; i < node.children.size(); ++i)
1145 {
1146 const size_t child_idx = self(self, *node.children(i).child, depth + 1);
1147 snap.nodes(out_idx).children.append(child_idx);
1148 }
1149 }
1150
1151 snap.nodes(out_idx).bbox = compute_mbr(node);
1152 return out_idx;
1153 };
1154
1155 snap.root = dfs(dfs, *root_, 0);
1156 return snap;
1157 }
1158};
1159
1160} // namespace Aleph
1161
1162#endif // TPL_R_TREE_H
Exception handling system with formatted messages for Aleph-w.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
static Array create_reserved(const size_t cap)
Build an empty array with room for at least cap items.
Definition tpl_array.H:194
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
Represents a point with rectangular coordinates in a 2D plane.
Definition point.H:221
Dynamic R-tree indexing axis-aligned rectangles by payload.
Definition tpl_r_tree.H:119
size_t height_
Number of node levels (0 when empty).
Definition tpl_r_tree.H:180
static Array< EntryT > quadratic_split(Array< EntryT > &entries)
Split an overflowed entry array in two using the quadratic heuristic.
Definition tpl_r_tree.H:310
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...
Definition tpl_r_tree.H:273
void for_each_intersecting_rec(const Node &node, const Rectangle &rect, F &f) const
Definition tpl_r_tree.H:759
static Array< EntryT > split_entries(Array< EntryT > &entries)
Split the entry array of node according to the active variant.
Definition tpl_r_tree.H:536
static Rectangle union_bbox(const Rectangle &a, const Rectangle &b)
Definition tpl_r_tree.H:195
static Geom_Number enlargement(const Rectangle &base, const Rectangle &added)
Area added to base by growing it to also cover added.
Definition tpl_r_tree.H:205
void reinsert_farthest(Node &node)
Move the R*-tree forced-reinsert candidates (the entries farthest from the node centre) out of the ov...
Definition tpl_r_tree.H:547
void add_entry(Entry entry)
Add a data entry without touching size_ (shared by insert and by erase-time reinsertion).
Definition tpl_r_tree.H:652
static size_t entry_count(const Node &node)
Definition tpl_r_tree.H:224
void clear_rstar_reinsert_state() noexcept
Drop R*-tree transient insertion state.
Definition tpl_r_tree.H:187
static Geom_Number overlap_area(const Rectangle &a, const Rectangle &b)
Area of the overlap between two rectangles (0 if disjoint).
Definition tpl_r_tree.H:211
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).
Definition tpl_r_tree.H:623
void insert(const Rectangle &bbox, const Payload &value)
Insert a (bbox, value) entry, copying value.
Definition tpl_r_tree.H:970
RTree(const RTree &other)
Deep-copy other (requires copy-constructible, movable Payload).
Definition tpl_r_tree.H:898
static size_t data_entry_count(const Node &node)
Definition tpl_r_tree.H:681
static bool box_contains_box(const Rectangle &outer, const Rectangle &inner)
True iff outer fully covers inner.
Definition tpl_r_tree.H:750
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.
Definition tpl_r_tree.H:230
static size_t choose_subtree(const Node &node, const Rectangle &bbox)
Choose the child of node into which bbox should be inserted.
Definition tpl_r_tree.H:247
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.
Definition tpl_r_tree.H:699
size_t height() const noexcept
Return the number of node levels (0 when empty, 1 for a lone leaf).
Definition tpl_r_tree.H:947
RTree() noexcept=default
Construct an empty R-tree.
bool rstar_reinsert_available_
Leaf-level reinsert not yet used this insert.
Definition tpl_r_tree.H:183
bool is_empty() const noexcept
Return true when the tree has no entries.
Definition tpl_r_tree.H:929
void insert(const Rectangle &bbox, Payload &&value)
Insert a (bbox, value) entry, moving value.
Definition tpl_r_tree.H:985
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
Definition tpl_r_tree.H:774
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.
Definition tpl_r_tree.H:938
std::unique_ptr< Node > insert_descend(Node &node, Entry entry)
Insert entry at the leaf level of node.
Definition tpl_r_tree.H:578
RTree & operator=(RTree &&other) noexcept
Move-assign from other, leaving it empty and valid.
Definition tpl_r_tree.H:880
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,...
Definition tpl_r_tree.H:427
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
Definition tpl_r_tree.H:810
std::unique_ptr< Node > root_
Definition tpl_r_tree.H:178
static std::unique_ptr< Node > clone_node(const Node &node)
Definition tpl_r_tree.H:790
bool verify() const
Verify the R-tree structural invariants.
void clear() noexcept
Remove all entries.
Definition tpl_r_tree.H:955
size_t size_
Number of stored data entries.
Definition tpl_r_tree.H:179
Array< Entry > rstar_reinsert_buffer_
Entries pending forced reinsertion.
Definition tpl_r_tree.H:184
static void collect_data_entries(Node &node, Array< Entry > &out)
Move every data entry in node's subtree into out.
Definition tpl_r_tree.H:669
An axis-aligned rectangle.
Definition point.H:1789
const Geom_Number & get_xmin() const
Gets the minimum x-coordinate.
Definition point.H:1815
const Geom_Number & get_ymax() const
Gets the maximum y-coordinate.
Definition point.H:1830
const Geom_Number & get_ymin() const
Gets the minimum y-coordinate.
Definition point.H:1820
const Geom_Number & get_xmax() const
Gets the maximum x-coordinate.
Definition point.H:1825
Point center() const
Calculates the center point of the rectangle.
Definition point.H:1906
Geom_Number area() const
Calculates the area of the rectangle.
Definition point.H:1888
__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)
Definition gmpfrxx.h:4138
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.
Definition ahAlgo.H:584
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.
Definition point.H:113
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.
Definition tpl_r_tree.H:100
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
STL namespace.
2D point and geometric utilities.
Internal-node entry: a child subtree plus its tight bounding box.
Definition tpl_r_tree.H:165
std::unique_ptr< Node > child
Owned child subtree.
Definition tpl_r_tree.H:167
Rectangle bbox
Tight MBR of child.
Definition tpl_r_tree.H:166
One node of a debug_snapshot, independent of Payload.
Definition tpl_r_tree.H:142
size_t depth
Root is 0, increasing towards the leaves.
Definition tpl_r_tree.H:145
bool is_leaf
True for leaf nodes (see entry_boxes).
Definition tpl_r_tree.H:144
Array< Rectangle > entry_boxes
Data-entry boxes stored here (leaves only).
Definition tpl_r_tree.H:147
Rectangle bbox
Tight MBR of this node.
Definition tpl_r_tree.H:143
Array< size_t > children
Indices into DebugSnapshot::nodes (internal nodes).
Definition tpl_r_tree.H:146
Full tree structure captured for visualization/debugging.
Definition tpl_r_tree.H:155
Array< DebugNode > nodes
Every node, in preorder.
Definition tpl_r_tree.H:156
size_t root
Index of the root in nodes.
Definition tpl_r_tree.H:157
A stored (bounding box, payload) pair.
Definition tpl_r_tree.H:130
Rectangle bbox
Axis-aligned bounding box.
Definition tpl_r_tree.H:131
Payload value
User payload associated with bbox.
Definition tpl_r_tree.H:132
A node is a leaf holding data or an internal node holding children.
Definition tpl_r_tree.H:172
Array< Child > children
Child entries (used iff not leaf).
Definition tpl_r_tree.H:175
Array< Entry > data
Data entries (used iff leaf).
Definition tpl_r_tree.H:174
static int * k
Dynamic array container with automatic resizing.
Comprehensive sorting algorithms and search utilities for Aleph-w.