pack_create.hpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. // Boost.Geometry Index
  2. //
  3. // R-tree initial packing
  4. //
  5. // Copyright (c) 2011-2017 Adam Wulkiewicz, Lodz, Poland.
  6. //
  7. // This file was modified by Oracle on 2019.
  8. // Modifications copyright (c) 2019 Oracle and/or its affiliates.
  9. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
  10. //
  11. // Use, modification and distribution is subject to the Boost Software License,
  12. // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  13. // http://www.boost.org/LICENSE_1_0.txt)
  14. #ifndef BOOST_GEOMETRY_INDEX_DETAIL_RTREE_PACK_CREATE_HPP
  15. #define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_PACK_CREATE_HPP
  16. #include <boost/core/ignore_unused.hpp>
  17. #include <boost/geometry/algorithms/expand.hpp>
  18. #include <boost/geometry/index/detail/algorithms/bounds.hpp>
  19. #include <boost/geometry/index/detail/algorithms/nth_element.hpp>
  20. #include <boost/geometry/index/detail/rtree/node/subtree_destroyer.hpp>
  21. #include <boost/geometry/algorithms/detail/expand_by_epsilon.hpp>
  22. namespace boost { namespace geometry { namespace index { namespace detail { namespace rtree {
  23. namespace pack_utils {
  24. template <std::size_t Dimension>
  25. struct biggest_edge
  26. {
  27. BOOST_STATIC_ASSERT(0 < Dimension);
  28. template <typename Box>
  29. static inline void apply(Box const& box, typename coordinate_type<Box>::type & length, std::size_t & dim_index)
  30. {
  31. biggest_edge<Dimension-1>::apply(box, length, dim_index);
  32. typename coordinate_type<Box>::type curr
  33. = geometry::get<max_corner, Dimension-1>(box) - geometry::get<min_corner, Dimension-1>(box);
  34. if ( length < curr )
  35. {
  36. dim_index = Dimension - 1;
  37. length = curr;
  38. }
  39. }
  40. };
  41. template <>
  42. struct biggest_edge<1>
  43. {
  44. template <typename Box>
  45. static inline void apply(Box const& box, typename coordinate_type<Box>::type & length, std::size_t & dim_index)
  46. {
  47. dim_index = 0;
  48. length = geometry::get<max_corner, 0>(box) - geometry::get<min_corner, 0>(box);
  49. }
  50. };
  51. template <std::size_t I>
  52. struct point_entries_comparer
  53. {
  54. template <typename PointEntry>
  55. bool operator()(PointEntry const& e1, PointEntry const& e2) const
  56. {
  57. return geometry::get<I>(e1.first) < geometry::get<I>(e2.first);
  58. }
  59. };
  60. template <std::size_t I, std::size_t Dimension>
  61. struct nth_element_and_half_boxes
  62. {
  63. template <typename EIt, typename Box>
  64. static inline void apply(EIt first, EIt median, EIt last, Box const& box, Box & left, Box & right, std::size_t dim_index)
  65. {
  66. if ( I == dim_index )
  67. {
  68. index::detail::nth_element(first, median, last, point_entries_comparer<I>());
  69. geometry::convert(box, left);
  70. geometry::convert(box, right);
  71. typename coordinate_type<Box>::type edge_len
  72. = geometry::get<max_corner, I>(box) - geometry::get<min_corner, I>(box);
  73. typename coordinate_type<Box>::type median
  74. = geometry::get<min_corner, I>(box) + edge_len / 2;
  75. geometry::set<max_corner, I>(left, median);
  76. geometry::set<min_corner, I>(right, median);
  77. }
  78. else
  79. nth_element_and_half_boxes<I+1, Dimension>::apply(first, median, last, box, left, right, dim_index);
  80. }
  81. };
  82. template <std::size_t Dimension>
  83. struct nth_element_and_half_boxes<Dimension, Dimension>
  84. {
  85. template <typename EIt, typename Box>
  86. static inline void apply(EIt , EIt , EIt , Box const& , Box & , Box & , std::size_t ) {}
  87. };
  88. } // namespace pack_utils
  89. // STR leafs number are calculated as rcount/max
  90. // and the number of splitting planes for each dimension as (count/max)^(1/dimension)
  91. // <-> for dimension==2 -> sqrt(count/max)
  92. //
  93. // The main flaw of this algorithm is that the resulting tree will have bad structure for:
  94. // 1. non-uniformly distributed elements
  95. // Statistic check could be performed, e.g. based on variance of lengths of elements edges for each dimension
  96. // 2. elements distributed mainly along one axis
  97. // Calculate bounding box of all elements and then number of dividing planes for a dimension
  98. // from the length of BB edge for this dimension (more or less assuming that elements are uniformly-distributed squares)
  99. //
  100. // Another thing is that the last node may have less elements than Max or even Min.
  101. // The number of splitting planes must be chosen more carefully than count/max
  102. //
  103. // This algorithm is something between STR and TGS
  104. // it is more similar to the top-down recursive kd-tree creation algorithm
  105. // using object median split and split axis of greatest BB edge
  106. // BB is only used as a hint (assuming objects are distributed uniformly)
  107. //
  108. // Implemented algorithm guarantees that the number of elements in nodes will be between Min and Max
  109. // and that nodes are packed as tightly as possible
  110. // e.g. for 177 values Max = 5 and Min = 2 it will construct the following tree:
  111. // ROOT 177
  112. // L1 125 52
  113. // L2 25 25 25 25 25 25 17 10
  114. // L3 5x5 5x5 5x5 5x5 5x5 5x5 3x5+2 2x5
  115. template <typename MembersHolder>
  116. class pack
  117. {
  118. typedef typename MembersHolder::node node;
  119. typedef typename MembersHolder::internal_node internal_node;
  120. typedef typename MembersHolder::leaf leaf;
  121. typedef typename MembersHolder::node_pointer node_pointer;
  122. typedef typename MembersHolder::size_type size_type;
  123. typedef typename MembersHolder::parameters_type parameters_type;
  124. typedef typename MembersHolder::translator_type translator_type;
  125. typedef typename MembersHolder::allocators_type allocators_type;
  126. typedef typename MembersHolder::box_type box_type;
  127. typedef typename geometry::point_type<box_type>::type point_type;
  128. typedef typename geometry::coordinate_type<point_type>::type coordinate_type;
  129. typedef typename detail::default_content_result<box_type>::type content_type;
  130. typedef typename detail::strategy_type<parameters_type>::type strategy_type;
  131. static const std::size_t dimension = geometry::dimension<point_type>::value;
  132. typedef typename rtree::container_from_elements_type<
  133. typename rtree::elements_type<leaf>::type,
  134. size_type
  135. >::type values_counts_container;
  136. typedef typename rtree::elements_type<internal_node>::type internal_elements;
  137. typedef typename internal_elements::value_type internal_element;
  138. typedef rtree::subtree_destroyer<MembersHolder> subtree_destroyer;
  139. public:
  140. // Arbitrary iterators
  141. template <typename InIt> inline static
  142. node_pointer apply(InIt first, InIt last,
  143. size_type & values_count,
  144. size_type & leafs_level,
  145. parameters_type const& parameters,
  146. translator_type const& translator,
  147. allocators_type & allocators)
  148. {
  149. typedef typename std::iterator_traits<InIt>::difference_type diff_type;
  150. diff_type diff = std::distance(first, last);
  151. if ( diff <= 0 )
  152. return node_pointer(0);
  153. typedef std::pair<point_type, InIt> entry_type;
  154. std::vector<entry_type> entries;
  155. values_count = static_cast<size_type>(diff);
  156. entries.reserve(values_count);
  157. expandable_box<box_type, strategy_type> hint_box(detail::get_strategy(parameters));
  158. for ( ; first != last ; ++first )
  159. {
  160. // NOTE: support for iterators not returning true references adapted
  161. // to Geometry concept and default translator returning true reference
  162. // An alternative would be to dereference the iterator and translate
  163. // in one expression each time the indexable was needed.
  164. typename std::iterator_traits<InIt>::reference in_ref = *first;
  165. typename translator_type::result_type indexable = translator(in_ref);
  166. // NOTE: added for consistency with insert()
  167. // CONSIDER: alternative - ignore invalid indexable or throw an exception
  168. BOOST_GEOMETRY_INDEX_ASSERT(detail::is_valid(indexable), "Indexable is invalid");
  169. hint_box.expand(indexable);
  170. point_type pt;
  171. geometry::centroid(indexable, pt);
  172. entries.push_back(std::make_pair(pt, first));
  173. }
  174. subtree_elements_counts subtree_counts = calculate_subtree_elements_counts(values_count, parameters, leafs_level);
  175. internal_element el = per_level(entries.begin(), entries.end(), hint_box.get(), values_count, subtree_counts,
  176. parameters, translator, allocators);
  177. return el.second;
  178. }
  179. private:
  180. template <typename BoxType, typename Strategy>
  181. class expandable_box
  182. {
  183. public:
  184. explicit expandable_box(Strategy const& strategy)
  185. : m_strategy(strategy), m_initialized(false)
  186. {}
  187. template <typename Indexable>
  188. explicit expandable_box(Indexable const& indexable, Strategy const& strategy)
  189. : m_strategy(strategy), m_initialized(true)
  190. {
  191. detail::bounds(indexable, m_box, m_strategy);
  192. }
  193. template <typename Indexable>
  194. void expand(Indexable const& indexable)
  195. {
  196. if ( !m_initialized )
  197. {
  198. // it's guaranteed that the Box will be initialized
  199. // only for Points, Boxes and Segments but that's ok
  200. // since only those Geometries can be stored
  201. detail::bounds(indexable, m_box, m_strategy);
  202. m_initialized = true;
  203. }
  204. else
  205. {
  206. detail::expand(m_box, indexable, m_strategy);
  207. }
  208. }
  209. void expand_by_epsilon()
  210. {
  211. geometry::detail::expand_by_epsilon(m_box);
  212. }
  213. BoxType const& get() const
  214. {
  215. BOOST_GEOMETRY_INDEX_ASSERT(m_initialized, "uninitialized envelope accessed");
  216. return m_box;
  217. }
  218. private:
  219. BoxType m_box;
  220. Strategy m_strategy;
  221. bool m_initialized;
  222. };
  223. struct subtree_elements_counts
  224. {
  225. subtree_elements_counts(size_type ma, size_type mi) : maxc(ma), minc(mi) {}
  226. size_type maxc;
  227. size_type minc;
  228. };
  229. template <typename EIt> inline static
  230. internal_element per_level(EIt first, EIt last,
  231. box_type const& hint_box,
  232. size_type values_count,
  233. subtree_elements_counts const& subtree_counts,
  234. parameters_type const& parameters,
  235. translator_type const& translator,
  236. allocators_type & allocators)
  237. {
  238. BOOST_GEOMETRY_INDEX_ASSERT(0 < std::distance(first, last) && static_cast<size_type>(std::distance(first, last)) == values_count,
  239. "unexpected parameters");
  240. if ( subtree_counts.maxc <= 1 )
  241. {
  242. // ROOT or LEAF
  243. BOOST_GEOMETRY_INDEX_ASSERT(values_count <= parameters.get_max_elements(),
  244. "too big number of elements");
  245. // if !root check m_parameters.get_min_elements() <= count
  246. // create new leaf node
  247. node_pointer n = rtree::create_node<allocators_type, leaf>::apply(allocators); // MAY THROW (A)
  248. subtree_destroyer auto_remover(n, allocators);
  249. leaf & l = rtree::get<leaf>(*n);
  250. // reserve space for values
  251. rtree::elements(l).reserve(values_count); // MAY THROW (A)
  252. // calculate values box and copy values
  253. // initialize the box explicitly to avoid GCC-4.4 uninitialized variable warnings with O2
  254. expandable_box<box_type, strategy_type> elements_box(translator(*(first->second)),
  255. detail::get_strategy(parameters));
  256. rtree::elements(l).push_back(*(first->second)); // MAY THROW (A?,C)
  257. for ( ++first ; first != last ; ++first )
  258. {
  259. // NOTE: push_back() must be called at the end in order to support move_iterator.
  260. // The iterator is dereferenced 2x (no temporary reference) to support
  261. // non-true reference types and move_iterator without boost::forward<>.
  262. elements_box.expand(translator(*(first->second)));
  263. rtree::elements(l).push_back(*(first->second)); // MAY THROW (A?,C)
  264. }
  265. #ifdef BOOST_GEOMETRY_INDEX_EXPERIMENTAL_ENLARGE_BY_EPSILON
  266. // Enlarge bounds of a leaf node.
  267. // It's because Points and Segments are compared WRT machine epsilon
  268. // This ensures that leafs bounds correspond to the stored elements
  269. // NOTE: this is done only if the Indexable is a different kind of Geometry
  270. // than the bounds (only Box for now). Spatial predicates are checked
  271. // the same way for Geometry of the same kind.
  272. if ( BOOST_GEOMETRY_CONDITION((
  273. ! index::detail::is_bounding_geometry
  274. <
  275. typename indexable_type<translator_type>::type
  276. >::value )) )
  277. {
  278. elements_box.expand_by_epsilon();
  279. }
  280. #endif
  281. auto_remover.release();
  282. return internal_element(elements_box.get(), n);
  283. }
  284. // calculate next max and min subtree counts
  285. subtree_elements_counts next_subtree_counts = subtree_counts;
  286. next_subtree_counts.maxc /= parameters.get_max_elements();
  287. next_subtree_counts.minc /= parameters.get_max_elements();
  288. // create new internal node
  289. node_pointer n = rtree::create_node<allocators_type, internal_node>::apply(allocators); // MAY THROW (A)
  290. subtree_destroyer auto_remover(n, allocators);
  291. internal_node & in = rtree::get<internal_node>(*n);
  292. // reserve space for values
  293. size_type nodes_count = calculate_nodes_count(values_count, subtree_counts);
  294. rtree::elements(in).reserve(nodes_count); // MAY THROW (A)
  295. // calculate values box and copy values
  296. expandable_box<box_type, strategy_type> elements_box(detail::get_strategy(parameters));
  297. per_level_packets(first, last, hint_box, values_count, subtree_counts, next_subtree_counts,
  298. rtree::elements(in), elements_box,
  299. parameters, translator, allocators);
  300. auto_remover.release();
  301. return internal_element(elements_box.get(), n);
  302. }
  303. template <typename EIt, typename ExpandableBox> inline static
  304. void per_level_packets(EIt first, EIt last,
  305. box_type const& hint_box,
  306. size_type values_count,
  307. subtree_elements_counts const& subtree_counts,
  308. subtree_elements_counts const& next_subtree_counts,
  309. internal_elements & elements,
  310. ExpandableBox & elements_box,
  311. parameters_type const& parameters,
  312. translator_type const& translator,
  313. allocators_type & allocators)
  314. {
  315. BOOST_GEOMETRY_INDEX_ASSERT(0 < std::distance(first, last) && static_cast<size_type>(std::distance(first, last)) == values_count,
  316. "unexpected parameters");
  317. BOOST_GEOMETRY_INDEX_ASSERT(subtree_counts.minc <= values_count,
  318. "too small number of elements");
  319. // only one packet
  320. if ( values_count <= subtree_counts.maxc )
  321. {
  322. // the end, move to the next level
  323. internal_element el = per_level(first, last, hint_box, values_count, next_subtree_counts,
  324. parameters, translator, allocators);
  325. // in case if push_back() do throw here
  326. // and even if this is not probable (previously reserved memory, nonthrowing pairs copy)
  327. // this case is also tested by exceptions test.
  328. subtree_destroyer auto_remover(el.second, allocators);
  329. // this container should have memory allocated, reserve() called outside
  330. elements.push_back(el); // MAY THROW (A?,C) - however in normal conditions shouldn't
  331. auto_remover.release();
  332. elements_box.expand(el.first);
  333. return;
  334. }
  335. size_type median_count = calculate_median_count(values_count, subtree_counts);
  336. EIt median = first + median_count;
  337. coordinate_type greatest_length;
  338. std::size_t greatest_dim_index = 0;
  339. pack_utils::biggest_edge<dimension>::apply(hint_box, greatest_length, greatest_dim_index);
  340. box_type left, right;
  341. pack_utils::nth_element_and_half_boxes<0, dimension>
  342. ::apply(first, median, last, hint_box, left, right, greatest_dim_index);
  343. per_level_packets(first, median, left,
  344. median_count, subtree_counts, next_subtree_counts,
  345. elements, elements_box,
  346. parameters, translator, allocators);
  347. per_level_packets(median, last, right,
  348. values_count - median_count, subtree_counts, next_subtree_counts,
  349. elements, elements_box,
  350. parameters, translator, allocators);
  351. }
  352. inline static
  353. subtree_elements_counts calculate_subtree_elements_counts(size_type elements_count, parameters_type const& parameters, size_type & leafs_level)
  354. {
  355. boost::ignore_unused(parameters);
  356. subtree_elements_counts res(1, 1);
  357. leafs_level = 0;
  358. size_type smax = parameters.get_max_elements();
  359. for ( ; smax < elements_count ; smax *= parameters.get_max_elements(), ++leafs_level )
  360. res.maxc = smax;
  361. res.minc = parameters.get_min_elements() * (res.maxc / parameters.get_max_elements());
  362. return res;
  363. }
  364. inline static
  365. size_type calculate_nodes_count(size_type count,
  366. subtree_elements_counts const& subtree_counts)
  367. {
  368. size_type n = count / subtree_counts.maxc;
  369. size_type r = count % subtree_counts.maxc;
  370. if ( 0 < r && r < subtree_counts.minc )
  371. {
  372. size_type count_minus_min = count - subtree_counts.minc;
  373. n = count_minus_min / subtree_counts.maxc;
  374. r = count_minus_min % subtree_counts.maxc;
  375. ++n;
  376. }
  377. if ( 0 < r )
  378. ++n;
  379. return n;
  380. }
  381. inline static
  382. size_type calculate_median_count(size_type count,
  383. subtree_elements_counts const& subtree_counts)
  384. {
  385. // e.g. for max = 5, min = 2, count = 52, subtree_max = 25, subtree_min = 10
  386. size_type n = count / subtree_counts.maxc; // e.g. 52 / 25 = 2
  387. size_type r = count % subtree_counts.maxc; // e.g. 52 % 25 = 2
  388. size_type median_count = (n / 2) * subtree_counts.maxc; // e.g. 2 / 2 * 25 = 25
  389. if ( 0 != r ) // e.g. 0 != 2
  390. {
  391. if ( subtree_counts.minc <= r ) // e.g. 10 <= 2 == false
  392. {
  393. //BOOST_GEOMETRY_INDEX_ASSERT(0 < n, "unexpected value");
  394. median_count = ((n+1)/2) * subtree_counts.maxc; // if calculated ((2+1)/2) * 25 which would be ok, but not in all cases
  395. }
  396. else // r < subtree_counts.second // e.g. 2 < 10 == true
  397. {
  398. size_type count_minus_min = count - subtree_counts.minc; // e.g. 52 - 10 = 42
  399. n = count_minus_min / subtree_counts.maxc; // e.g. 42 / 25 = 1
  400. r = count_minus_min % subtree_counts.maxc; // e.g. 42 % 25 = 17
  401. if ( r == 0 ) // e.g. false
  402. {
  403. // n can't be equal to 0 because then there wouldn't be any element in the other node
  404. //BOOST_GEOMETRY_INDEX_ASSERT(0 < n, "unexpected value");
  405. median_count = ((n+1)/2) * subtree_counts.maxc; // if calculated ((1+1)/2) * 25 which would be ok, but not in all cases
  406. }
  407. else
  408. {
  409. if ( n == 0 ) // e.g. false
  410. median_count = r; // if calculated -> 17 which is wrong!
  411. else
  412. median_count = ((n+2)/2) * subtree_counts.maxc; // e.g. ((1+2)/2) * 25 = 25
  413. }
  414. }
  415. }
  416. return median_count;
  417. }
  418. };
  419. }}}}} // namespace boost::geometry::index::detail::rtree
  420. #endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_PACK_CREATE_HPP