c++ - 我是否需要遍历 boost rtree 的层次结构以达到最大效率?

标签 c++ optimization boost boost-geometry r-tree

经过一些阅读后,我了解到层次结构遍历虽然可能在 boost rtree 中并未得到官方支持。我有几个不同的用例,我可以在没有层次结构遍历的情况下进行管理,但我不确定效率。因此,我正在寻求有关 boost rtree 如何在内部工作以及这些用例的最佳实践是什么的建议。

案例 1 - 我有 2 棵树,我想过滤这两棵树以查找与另一棵树中至少一个元素相交的元素。我有下面的代码可以执行此操作并提供我想要的结果:

    std::set<int> results2;
    std::vector<rtree3d_item> tempResults, results1;
    std::vector<rtree3d_item>::iterator it;
    tree1->query(bgi::satisfies(
        [&](const rtree3d_item& item) {
            tempResults.clear();
            tree2->query(bgi::intersects(item.first), std::back_inserter(tempResults));
            for (it = tempResults.begin(); it < tempResults.end(); it++)
            {
                results2.insert(it->second);
            }
            return tempResults.size() > 0;
        }
    ), std::back_inserter(results1));

虽然我得到了我想要的结果,但该方法似乎不是最优的。我传递给 satisfies() 的 lambda 表达式对 tree1 中的每个叶节点运行一次。如果我可以遍历树的层次结构,我就可以测试父节点的大框并排除大块的 tree1 并使过程更加高效。几乎就像 tree1 是一个树结构是没有用的。

情况 2 - 我只想查询 rtree 以查找与球体相交的所有项目。我使用谓词 lambda 表达式来实现:

bgi::satisfies(
        [=](const rtree3d_item &item) {
            return bg::distance(item.first, cpt) < radius;
        })

该表达式对内部 rtree 的每个叶节点运行一次,这又显得很浪费。如果我对父节点进行此测试,我可以一次排除多个叶节点。

似乎每当我测试 rtree 满足条件时我都会遇到同样的情况 - (如果边界框不满足条件,其中包含的任何边界框也将不满足条件)。我的意思是,如果我要一直测试所有叶节点,那么拥有“树”结构有什么意义呢?为什么 boost 官方不支持遍历树的层次结构的方法?

我找到了一个资源,其中讨论了不受支持的非官方方式 ( link ) 来做这件事,但我想尝试官方的、受支持的方式来优化我的代码。

仅供引用,我在 C++ 方面的经验有限,因此欢迎提供所有建议,谢谢!

最佳答案

Why doesn't boost officially support ways to traverse the hierarchy of the tree ?

猜测:

  • 他们使用友好的 API 实现高级原语。在文档化的界面中不包括较低级别可以更灵活地迭代这些界面的设计,而不会给库的用户带来麻烦。因此,最终结果将严格来说是更好、更底层的接口(interface),一旦稳定下来就可以记录下来。

  • 遍历的语义将与平衡/结构化策略密切相关。这意味着在所有情况下都很难理解/记录遍历顺序的含义,这可能是错误的来源。没有将其记录在案向用户发出信号(他们可以使用它,但后果自负)


案例一

同意。我会说你最好在第一棵树上做一个 BFS,然后查询与第二棵树的交集。这样,您可以快速删除树(子树)中不感兴趣的“部分”。

基于代码 linked by the library dev here ,我想出了一个粗略的、最小的访问者:

namespace rtree = bgi::detail::rtree;

template <typename Predicate, typename Value, typename Options, typename Box, typename Allocators>
struct BFSQuery : public rtree::visitor<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag, true>::type
{
    typedef typename rtree::internal_node<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type internal_node;
    typedef typename rtree::leaf<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type leaf;

    inline BFSQuery(Predicate const& p) : pr(p) {}

    inline void operator()(internal_node const& n) {
        for (auto&& [bounds, node] : rtree::elements(n))
            if (pr(bounds))
                rtree::apply_visitor(*this, *node);
    }

    inline void operator()(leaf const& n) {
        for (auto& item : rtree::elements(n))
            if (pr(item)) results.insert(&item);
    }

    Predicate const& pr;

    std::set<Value const*> results;
};

Note: one random choice was to deduplicate results using a std::set, which has the side-effect that results will be in unspecified order ("address order" if you will).

使用这个访问者,算法本身可以非常简单:

template <typename TreeA, typename TreeB, typename F>
void tree_insersects(TreeA const& a, TreeB const& b, F action) {
    using V = rtree::utilities::view<TreeA>;
    V av(a);

    auto const pred = [&b](auto const& bounds) {
        return bgi::qbegin(b, bgi::intersects(bounds)) != bgi::qend(b);
    };

    BFSQuery<
      decltype(pred),
      typename V::value_type,
      typename V::options_type,
      typename V::box_type,
      typename V::allocators_type
    > vis(pred);

    av.apply_visitor(vis);

    auto tr = av.translator();
    for (auto* hit : vis.results)
        action(tr(*hit));
}

注意尽可能通用。

使用它:

Live On Coliru

int main() {
    using Box = bg::model::box<bg::model::d2::point_xy<int> >;

    // generate some boxes with nesting
    bgi::rtree<Box, bgi::rstar<5>> a;
    for (auto [k,l] : { std::pair(0, 1), std::pair(-1, 2) }) {
        std::generate_n(bgi::insert_iterator(a), 10,
            [k,l,i=1]() mutable { Box b{ {i+k,i+k}, {i+l,i+l} }; i+=2; return b; });
    }

    // another simple tree to intersect with
    bgi::rtree<Box, bgi::quadratic<16> > b;
    b.insert({ {9,9}, {12,12} });
    b.insert({ {-9,-9}, {1,2} });

    Demo::tree_insersects(a, b, [](auto& value) {
        std::cout << "intersects: " << bg::dsv(value) << "\n";
    });
}

打印(顺序可能不同):

intersects: ((1, 1), (2, 2))
intersects: ((0, 0), (3, 3))
intersects: ((11, 11), (12, 12))
intersects: ((10, 10), (13, 13))
intersects: ((12, 12), (15, 15))
intersects: ((6, 6), (9, 9))
intersects: ((8, 8), (11, 11))
intersects: ((9, 9), (10, 10))

案例2

我认为您可以使用标准查询谓词实现此目的:

for (auto& value : boost::make_iterator_range(bgi::qbegin(a, bgi::intersects(sphere)), {})) {
    std::cout << "intersects: " << bg::dsv(value) << "\n";
}

查看 Live On Coliru


完整列表案例#1

后代的tree_insersects算法

Live On Coliru

#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/geometry/index/detail/utilities.hpp>
#include <boost/geometry/index/predicates.hpp>
#include <iostream>

namespace bg = boost::geometry;
namespace bgi = bg::index;

namespace Demo {
    namespace rtree = bgi::detail::rtree;

    template <typename Predicate, typename Value, typename Options, typename Box, typename Allocators>
    struct BFSQuery : public rtree::visitor<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag, true>::type
    {
        typedef typename rtree::internal_node<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type internal_node;
        typedef typename rtree::leaf<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type leaf;

        inline BFSQuery(Predicate const& p) : pr(p) {}

        inline void operator()(internal_node const& n) {
            for (auto&& [bounds, node] : rtree::elements(n)) {
                if (pr(bounds))
                    rtree::apply_visitor(*this, *node);
            }
        }

        inline void operator()(leaf const& n) {
            for (auto& item : rtree::elements(n))
                if (pr(item)) results.insert(&item);
        }

        Predicate const& pr;

        std::set<Value const*> results;
    };

    template <typename TreeA, typename TreeB, typename F> void tree_insersects(TreeA const& a, TreeB const& b, F action) {
        using V = rtree::utilities::view<TreeA>;
        V av(a);

        auto const pred = [&b](auto const& bounds) {
            return bgi::qbegin(b, bgi::intersects(bounds)) != bgi::qend(b);
        };

        BFSQuery<
          decltype(pred),
          typename V::value_type,
          typename V::options_type,
          typename V::box_type,
          typename V::allocators_type
        > vis(pred);

        av.apply_visitor(vis);

        auto tr = av.translator();
        for (auto* hit : vis.results)
            action(tr(*hit));
    }
}

int main() {
    using Box = bg::model::box<bg::model::d2::point_xy<int> >;

    // generate some boxes with nesting
    bgi::rtree<Box, bgi::rstar<5>> a;
    for (auto [k,l] : { std::pair(0, 1), std::pair(-1, 2) }) {
        std::generate_n(bgi::insert_iterator(a), 10,
            [k,l,i=1]() mutable { Box b{ {i+k,i+k}, {i+l,i+l} }; i+=2; return b; });
    }

    // another simple tree to intersect with
    bgi::rtree<Box, bgi::quadratic<16> > b;
    b.insert({ {9,9}, {12,12} });
    b.insert({ {-9,-9}, {1,2} });

    Demo::tree_insersects(a, b, [](auto& value) {
        std::cout << "intersects: " << bg::dsv(value) << "\n";
    });
}

关于c++ - 我是否需要遍历 boost rtree 的层次结构以达到最大效率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57613782/

相关文章:

python - 两个for循环的优化

c++ - 如何在 Windows 上解析由 std::put_time ("%x") 创建的字符串?

c++ - ALSA 回调(SIGIO 处理程序)有时会在 boost::posix_time::microsec_clock::local_time() 中的某处挂起

c++ - 优化文件打开和读取

c++ - 使用 asio boost 线程池 : Threads randomly don't execute

c++ - 修改递归字符串反转函数

c++ - 使用局部静态 std::once_flag 和局部静态指针对静态变量进行线程安全初始化

c++ - 函数指针的取消引用是如何发生的?

c++ - CMD 提示符 C++ : Limiting literals entered on screen

python - 在 Django 中分析 View 的最佳方式是什么?