/usr/include/terralib/kernel/TeKdTree.h is in libterralib-dev 4.3.0+dfsg.2-4build2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 | /************************************************************************************
TerraLib - a library for developing GIS applications.
Copyright © 2001-2007 INPE and Tecgraf/PUC-Rio.
This code is part of the TerraLib library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
You should have received a copy of the GNU Lesser General Public
License along with this library.
The authors reassure the license terms regarding the warranties.
They specifically disclaim any warranties, including, but not limited to,
the implied warranties of merchantability and fitness for a particular purpose.
The library provided hereunder is on an "as is" basis, and the authors have no
obligation to provide maintenance, support, updates, enhancements, or modifications.
In no event shall INPE and Tecgraf / PUC-Rio be held liable to any party for direct,
indirect, special, incidental, or consequential damages arising out of the use
of this library and its documentation.
*************************************************************************************/
/*! \file TeKdTree.h
\brief This file contains an implementation of kdtree data structures in main memory for two dimensions.
\note These data structures and algorithms MUST BE USED ONLY BY TerraLib kernel and should NOT be used by anyone because
THIS IS FOR INTERNAL USE ONLY.
\author Gilberto Ribeiro de Queiroz <gribeiro@dpi.inpe.br>
*/
#ifndef __TERRALIB_INTERNAL_KDTREE_H
#define __TERRALIB_INTERNAL_KDTREE_H
#include "TeGeometry.h"
/**
* WARNING: These data structures and algorithms MUST BE USED ONLY BY TerraLib kernel and should NOT be used by anyone because
* the support and interfaces can be changed in future. THIS IS FOR INTERNAL USE ONLY.
*
*/
namespace TeSAM
{
/** @defgroup PartitionAlgorithms Partition Algorithms
* Partition Algorithms.
* @{
*/
//! This function partition the conteiner in two parts: k-1 elements to the left (elements less than or equals to k-th element) and the right part with all other elements (elements greater than or equal to k-th element)
/*
\param A Conteiner of elements to partition
\param kthElement Position of the k-th element, around the conteiner will be pertitionated
\param firstElement Position of the first element
\param lastElement Position of the las element
\param compFunctor Functor to compare elements: implements the function "less than"
*/
template<class CONTAINER, class COMPFUNCTOR>
void TeHoareFind(CONTAINER& A, const unsigned int& kthElement, const unsigned int& firstElement, const unsigned int& lastElement, const COMPFUNCTOR& compFunctor)
{
unsigned int m = firstElement;
unsigned int n = lastElement;
// Test if the median is in the bounds
if((kthElement < firstElement) || (kthElement > lastElement))
return;
// Do conteiner partition
while(m < n)
{
unsigned int i = m;
unsigned int j = n;
typename CONTAINER::value_type r = A[kthElement];
while(i <= j)
{
while(compFunctor(A[i], r))
++i;
while(compFunctor(r, A[j]))
--j;
if(i <= j)
{
typename CONTAINER::value_type w = A[i];
A[i] = A[j];
A[j] = w;
++i;
--j;
}
}
if(kthElement <= j) // if the meet point was to the right, so all points above j are greater than the k-th element
n = j;
else if(i <= kthElement) // otherwise, if the meeting point was to the left of k-th, so all elements before i are already in the correct location
m = i;
else
break;
}
}
//! Partition the conteiner like a bidimensional K-d Tree using Hoare algorithms
/*
\param dataSet Conteinet elements to be sorted like a K-dTree
\param first Position of the first element in conteiner, where the sort will begin
\param last Position of the last element, where the sort ends
\param level Indicates the axis to begin the sort ('x' or 'y') and is used during the recursion process
\param lessThanCompFunctorByX Functor to compare elements along the 'x' axis
\param lessThanCompFunctorByY Functor to compare elements along the 'y' axis
The expected complexity is O(N log N), where N is the number of elements in conteiner.
*/
template<class CONTAINER, class LESSTHANX, class LESSTHANY>
void kdsort(CONTAINER& dataSet, const unsigned int& first, const unsigned int& last, const char& level, const LESSTHANX& lessThanCompFunctorByX, const LESSTHANY& lessThanCompFunctorByY)
{
const unsigned int kth = (last - first + 1u) / 2u;
if(level == 'x')
{
// Move data around X axis
TeHoareFind(dataSet, first + kth, first, last, lessThanCompFunctorByX);
// Recursive sort the left half and right half
if((first + kth) > first)
kdsort(dataSet, first, first + kth - 1u, 'y', lessThanCompFunctorByX, lessThanCompFunctorByY);
if((first + kth) < last)
kdsort(dataSet, first + kth + 1u, last, 'y', lessThanCompFunctorByX, lessThanCompFunctorByY);
}
else
{
// Move data around Y axis
TeHoareFind(dataSet, first + kth, first, last, lessThanCompFunctorByY);
// Recursive sort the left half and right half
if((first + kth) > first)
kdsort(dataSet, first, first + kth - 1u, 'x', lessThanCompFunctorByX, lessThanCompFunctorByY);
if((first + kth) < last)
kdsort(dataSet, first + kth + 1u, last, 'x', lessThanCompFunctorByX, lessThanCompFunctorByY);
}
}
/** @} */
//! Kd-tree node type for nodes with single elements (used by template instantiation).
struct TL_DLL kd_node_data_single_tag {};
//! Kd-Tree node type for nodes with multuple elements (used by template instantiation).
struct TL_DLL kd_node_data_set_tag {};
//! Class that represents a node of a TeKdTree
/*!
Each node contains a pointer to its left and right subtree (NULL if it is not set),
one key used for insertion of the data into the tree.
WARNING: <BR>
1. The key must have methods called x() and y(). <BR>
2. These kind of node stores the data in each node. <BR>
3. The nodes may contains one single element (kd_node_data_single_tag) or a set of values (kd_node_data_set_tag). <BR>
4. If the node type is kd_node_data_single_tag than NodeData and NodeDataItem are the same types. And if
one entry with the same key already exist, so they will be overwrite. <BR>
5. If the node type is kd_node_data_set_tag than NodeData mus have a method called push_back(NodeDataItem)
that permits to store elements with the same key in the node. <BR>
*/
template<class NodeKey, class NodeData, class NodeDataItem,
class NodeDataTag = kd_node_data_single_tag>
class TeKdTreeNode
{
protected:
//! The key used to access this record
NodeKey key_;
//! The data stored in this record
NodeData data_;
//! Pointer to the left sub-tree.
TeKdTreeNode* left_;
//! Pointer to the right sub-tree.
TeKdTreeNode* right_;
public:
//! Export key type.
typedef NodeKey kdKey;
//! Export data type.
typedef NodeData kdData;
//! Export data item type.
typedef NodeDataItem kdDataItem;
//! Export data type.
typedef NodeDataTag kdDataTag;
//! Constructor
TeKdTreeNode(const NodeKey& k)
: key_(k), left_(0), right_(0)
{
}
//! Sets the key to the node
void setKey(const NodeKey& k)
{
key_ = k;
}
//! Returns a reference to node key
const NodeKey& getKey(void) const
{
return key_;
}
//! Sets the data in the node
void setData(const NodeData& data)
{
data_ = data;
}
//! Returns a reference to data node
NodeData& getData(void)
{
return data_;
}
//! Sets the left child pointer
void setLeft(TeKdTreeNode* node)
{
left_ = node;
}
//! Sets the right child pointer
void setRight(TeKdTreeNode* node)
{
right_ = node;
}
//! Accessor for left child
TeKdTreeNode* getLeft(void) const
{
return left_;
}
//! Accessor for right child
TeKdTreeNode* getRight(void) const
{
return right_;
}
//! Method to check if this has a left child
bool hasLeft(void) const
{
return (left_ != 0);
}
//! Method to check if a this has a right child
bool hasRight(void) const
{
return (right_ != 0);
}
//! Method to check if this has no children
bool isLeaf(void) const
{
return !(hasLeft() || hasRight());
}
//! Method to count the number of nodes below this
unsigned int descendants(void) const
{
unsigned int totalLeft = 0u;
unsigned int totalRight = 0u;
if(hasLeft())
totalLeft = 1u + getLeft()->descendants();
if(hasRight())
totalRight = 1u + getRight()->descendants();
return (totalLeft + totalRight);
}
private:
//! No copy allowed
TeKdTreeNode(const TeKdTreeNode& other);
//! No copy allowed
TeKdTreeNode& operator=(const TeKdTreeNode& other);
}; // end of class TeKdTreeNode
//! A base class for Kd-Tree structures
/*!
This class implements only common kdtree methods and properties.
*/
template<class KdTreeNode>
class TeBasicKdTree
{
protected:
//! Pointer to the root node
KdTreeNode* root_;
//! Bounding box of all nodes
TeBox mbr_;
//! The size of the K-d Tree (number of nodes)
unsigned int size_;
public:
//! Constructor
TeBasicKdTree(const TeBox& mbr)
: root_(0), mbr_(mbr), size_(0u)
{
}
//! Destructor
~TeBasicKdTree()
{
clear();
}
//! Clear all tree nodes
void clear(void)
{
if(root_)
{
erase(root_);
root_ = 0;
size_ = 0;
}
}
//! The number of tree nodes
const unsigned int& size(void) const
{
return size_;
}
//! Return true if the tree is empty
bool isEmpty(void) const
{
return root_ == 0;
}
//! Sets the bounding box of all elements in the tree
void setBox(const TeBox& mbr)
{
mbr_ = mbr;
}
//! Sets the bounding box of all elements in the tree
const TeBox& getBox(void) const
{
return mbr_;
}
protected:
//! Erases a node from the tree and all nodes below it.
void erase(KdTreeNode* node)
{
if(node->hasLeft())
erase(node->getLeft());
if(node->hasRight())
erase(node->getRight());
delete node;
return;
}
private:
//! No copy allowed
TeBasicKdTree(const TeBasicKdTree& other);
//! No copy allowed
TeBasicKdTree& operator=(const TeBasicKdTree& other);
};
//! A class that represents a two dimensional K-d Tree (2-d Tree)
/*!
WARNING:
1. This type of tree stores the data into nodes (not only in the leafs node).
2. This tree may be built by two ways: <BR>
2.1. Inserting each element in the tree. In this case the tree can becomes unbalanced, but in practical
cases this is not the expected, and is the best way to construct the tree (faster way). <BR>
2.2. Passing a container with pairs (key/data-item) and using the method buildOptimized after
calling kdsort. The tree built this way is almost balanced but will be
construct in time O(N log N).<BR>
WARNING: In this case items with the same key will be stores in different nodes!<BR>
3. This type of tree may be of special interest of BOX SEARCH QUERIES.
4. If the node type is kd_node_data_single_tag than NodeData and NodeDataItem are the same types. And if
one entry with the same key already exist, so they will be overwrite.
5. If the node type is kd_node_data_set_tag than NodeData mus have a method called push_back(NodeDataItem)
that permits to store elements with the same key in the node.
*/
template<class KdTreeNode>
class TeKdTree : public TeBasicKdTree<KdTreeNode>
{
using TeBasicKdTree<KdTreeNode>::root_;
using TeBasicKdTree<KdTreeNode>::size_;
using TeBasicKdTree<KdTreeNode>::mbr_;
public:
//! Export key type.
typedef typename KdTreeNode::kdKey kdKey;
//! Export data type.
typedef typename KdTreeNode::kdData kdData;
//! Export data item type.
typedef typename KdTreeNode::kdDataItem kdDataItem;
//! Export data type.
typedef typename KdTreeNode::kdDataTag kdDataTag;
//! Constructor
TeKdTree(const TeBox& mbr)
: TeBasicKdTree<KdTreeNode>(mbr)
{
}
//! Inserts the data with a given key in tree
inline void insert(const kdKey& key, const kdDataItem& item);
//! Inserts the data in the tree and and keeps it balanced: the kdsort algorithm must be called before
void buildOptimized(vector<pair<kdKey, kdDataItem> >& dataSet)
{
const unsigned int last = dataSet.size() - 1u;
root_ = buildOptimized(dataSet, 0u, last);
}
//! Range search query.
void search(const TeBox& rect, vector<KdTreeNode*>& report) const
{
if(root_)
search(rect, root_, 'x', report);
return;
}
protected:
//! Inserts data for single nodes, i.e., nodes that stores only one element
void insertData(KdTreeNode*& node, const kdDataItem& data, const kd_node_data_single_tag&)
{
node->setData(data);
}
//! Inserts data for set nodes, i.e., nodes that may stores many element
void insertData(KdTreeNode*& node, const kdDataItem& data, const kd_node_data_set_tag&)
{
node->getData().push_back(data);
}
//! Recursive range query
inline void search(const TeBox& rect, KdTreeNode* node, const char& level, vector<KdTreeNode*>& report) const;
//! Builds the tree recursively
KdTreeNode* buildOptimized(vector<pair<kdKey, kdDataItem> >& dataSet, const unsigned int& first, const unsigned int& last)
{
const unsigned int kth = (last - first + 1u) / 2u;
KdTreeNode* newNode = new KdTreeNode(dataSet[first + kth].first);
newNode->setData(dataSet[first + kth].second);
++size_;
if((first + kth) > first)
newNode->setLeft(buildOptimized(dataSet, first, first + kth - 1u));
if((first + kth) < last)
newNode->setRight(buildOptimized(dataSet, first + kth + 1u, last));
return newNode;
}
private:
//! No copy allowed
TeKdTree(const TeKdTree& other);
//! No copy allowed
TeKdTree& operator=(const TeKdTree& other);
}; // end class TeKdTree
template<class KdTreeNode>
void TeKdTree<KdTreeNode>::insert(const kdKey& key, const kdDataItem& item)
{
if(root_ == 0)
{
root_ = new KdTreeNode(key);
insertData(root_, item, kdDataTag());
}
else
{
char level = 'x';
bool left = false;
KdTreeNode* x = root_;
KdTreeNode* y = 0;
while(x != 0)
{
y = x;
if(level == 'x')
{
if(key.x() > x->getKey().x()) // if the key is greater than, inserts in the right subtree
{
x = x->getRight();
left = false;
}
else if(key.x() < x->getKey().x()) // if the key is smaller than, inserts in the left subtree
{
x = x->getLeft();
left = true;
}
else if(key.y() == x->getKey().y()) // if the key already exist, in the case of single node the data will be overwrite and in the case of set node they will push_back the item
{
insertData(x, item, kdDataTag());
return;
}
else // found the same axis partition, so go left
{
x = x->getLeft();
left = true;
}
level = 'y';
}
else
{
if(key.y() > x->getKey().y())
{
x = x->getRight();
left = false;
}
else if(key.y() < x->getKey().y())
{
x = x->getLeft();
left = true;
}
else if(key.x() == x->getKey().x())
{
insertData(x, item, kdDataTag());
return;
}
else
{
x = x->getLeft();
left = true;
}
level = 'x';
}
}
KdTreeNode* newNode = new KdTreeNode(key);
insertData(newNode, item, kdDataTag());
if(left)
y->setLeft(newNode);
else
y->setRight(newNode);
}
++size_;
return;
}
template<class KdTreeNode>
void TeKdTree<KdTreeNode>::search(const TeBox& rect, KdTreeNode* node, const char& level, vector<KdTreeNode*>& report) const
{
if((node->getKey().x() >= rect.x1_) && (node->getKey().x() <= rect.x2_) &&
(node->getKey().y() >= rect.y1_) && (node->getKey().y() <= rect.y2_))
report.push_back(node);
if(level == 'x')
{
if(node->hasLeft())
if(node->getKey().x() >= rect.x1_)
search(rect, node->getLeft(), 'y', report);
if(node->hasRight())
if(node->getKey().x() <= rect.x2_)
search(rect, node->getRight(), 'y', report);
}
else
{
if(node->hasLeft())
if(node->getKey().y() >= rect.y1_)
search(rect, node->getLeft(), 'x', report);
if(node->hasRight())
if(node->getKey().y() <= rect.y2_)
search(rect, node->getRight(), 'x', report);
}
return;
}
//! Class that represents a node of a TeAdaptativeKdTree
/*!
Each node contains a pointer to its left and right subtree (NULL if it is not set),
a discriminator that indicates the axis of partition, the partition key and
a set of data-items.
WARNING:
1. The key must have methods called x() and y().
2. These kind of node stores the data only in the leafs.
3. The leaf nodes contains a set of values that forms a bucket (the size is controlled by the tree methods tha use this class).
*/
template<class NodeKey, class NodeData, class NodeDataItem>
class TeAdaptativeKdTreeNode
{
protected:
//! The key used to access this record
double key_;
//! The data stored in this record
NodeData data_;
//! The discriminator used in partition
char discriminator_;
//! Pointer to the left sub-tree.
TeAdaptativeKdTreeNode* left_;
//! Pointer to the right sub-tree.
TeAdaptativeKdTreeNode* right_;
public:
//! Export key type.
typedef NodeKey kdKey;
//! Export data type.
typedef NodeData kdData;
//! Export data item type.
typedef NodeDataItem kdDataItem;
//! Constructor
TeAdaptativeKdTreeNode(const double& k)
: key_(k), discriminator_('x'), left_(0), right_(0)
{ }
//! Sets the key to the node
void setKey(const double& k)
{
key_ = k;
}
//! Returns a reference to node key
const double& getKey(void) const
{
return key_;
}
//! Sets the data in the node
void setData(const NodeData& data)
{
data_ = data;
}
//! Returns a reference to data node
NodeData& getData(void)
{
return data_;
}
//! Sets the data in the node
void setDiscriminator(const char& d)
{
discriminator_ = d;
}
//! Returns a reference to discriminator
const char& getDiscriminator(void) const
{
return discriminator_;
}
//! Sets the left child pointer
void setLeft(TeAdaptativeKdTreeNode* node)
{
left_ = node;
}
//! Sets the right child pointer
void setRight(TeAdaptativeKdTreeNode* node)
{
right_ = node;
}
//! Accessor for left child
TeAdaptativeKdTreeNode* getLeft(void) const
{
return left_;
}
//! Accessor for right child
TeAdaptativeKdTreeNode* getRight(void) const
{
return right_;
}
//! Method to check if this has a left child
bool hasLeft(void) const
{
return (left_ != 0);
}
//! Method to check if a this has a right child
bool hasRight(void) const
{
return (right_ != 0);
}
//! Method to check if this has no children
bool isLeaf(void) const
{
return !(hasLeft() || hasRight());
}
//! Method to count the number of nodes below this
unsigned int descendants(void) const
{
unsigned int totalLeft = 0u;
unsigned int totalRight = 0u;
if(hasLeft())
totalLeft = 1u + getLeft()->descendants();
if(hasRight())
totalRight = 1u + getRight()->descendants();
return (totalLeft + totalRight);
}
private:
//! No copy allowed
TeAdaptativeKdTreeNode(const TeAdaptativeKdTreeNode& other);
//! No copy allowed
TeAdaptativeKdTreeNode& operator=(const TeAdaptativeKdTreeNode& other);
}; // end of class TeAdaptativeKdTreeNode
//! A class that represents a two dimensional K-d Tree (2-d Tree) that store data-elements into the leafs
/*!
WARNING:
1. This type of tree stores the data only in the leaf nodes.
2. The process of construction expect that the tree is almost balanced
3. This type of tree may be of special interest of NEAREST NEIGHBOR SEARCH QUERIES.
4. After a box search it will be necessary to do a refinement.
*/
template<class KdTreeNode>
class TeAdaptativeKdTree : public TeBasicKdTree<KdTreeNode>
{
using TeBasicKdTree<KdTreeNode>::root_;
using TeBasicKdTree<KdTreeNode>::size_;
using TeBasicKdTree<KdTreeNode>::mbr_;
protected:
//! Bucket size (maximum number of elements in each node)
unsigned int bucketSize_;
public:
//! Export key type.
typedef typename KdTreeNode::kdKey kdKey;
//! Export data type.
typedef typename KdTreeNode::kdData kdData;
//! Export data item type.
typedef typename KdTreeNode::kdDataItem kdDataItem;
//! Export node type.
typedef KdTreeNode kdNode;
//! Constructor
TeAdaptativeKdTree(const TeBox& box, const unsigned int& bucketSize = 12)
: TeBasicKdTree<KdTreeNode>(box), bucketSize_(bucketSize)
{
}
//! Sets bucket size for leaf nodes
void setBucketSize(const unsigned int& size)
{
bucketSize_ = size;
}
//! Sets bucket size for leaf nodes
const unsigned int& getBucketSize(void) const
{
return bucketSize_;
}
//! Inserts the data set into the tree
void build(vector<pair<kdKey, kdDataItem> >& dataSet)
{
root_ = build(dataSet, 0.0, mbr_);
}
//! Search the nearest data in nodes: you must pass an array of kdDataItem of size "k" with coordinates values (X() and Y()) adjusted to TeMAXFLOAT (this dummy values will be replaced at processing time), and if not all neighbors are found so sqrDists will contains TeMAXFLOAT in array index
void nearestNeighborSearch(const kdKey& key, vector<kdDataItem>& report, vector<double>& sqrDists, const unsigned int& k) const
{
if(root_)
{
sqrDists.clear();
for(unsigned int i = 0; i < k; ++i)
sqrDists.push_back(TeMAXFLOAT);
TeBox rect(-TeMAXFLOAT, -TeMAXFLOAT, +TeMAXFLOAT, +TeMAXFLOAT);
nearestNeighborSearch(root_, key, report, sqrDists, rect);
}
}
//! Range search query.
void search(const TeBox& rect, vector<KdTreeNode*>& report) const
{
if(root_)
search(rect, root_, report);
return;
}
//! Range search query: the refinement is already done
inline void search(const TeBox& rect, vector<kdDataItem>& report) const;
protected:
//! Build the tree recursivily
inline KdTreeNode* build(vector<pair<kdKey, kdDataItem> >& dataSet, double averageValue, const TeBox& mbr);
//! Recursive range query.
inline void search(const TeBox& rect, KdTreeNode* node, vector<KdTreeNode*>& report) const;
//! Recursive nearest neighbor search
inline void nearestNeighborSearch(KdTreeNode* node, const kdKey& key, vector<kdDataItem>& report, vector<double>& sqrDists, TeBox& rect) const;
//! Update neighbor list
inline void update(KdTreeNode* node, const kdKey& key, vector<kdDataItem>& report, vector<double>& sqrDists, TeBox& rect) const;
//! Returns the average value along the axis
double average(vector<pair<kdKey, kdDataItem> >& dataSet, const char& discriminator) const
{
const unsigned int size = dataSet.size();
double medianValue = 0.0;
if(discriminator == 'x')
{
for(unsigned int i = 0; i < size; ++i)
medianValue += dataSet[i].first.x();
return medianValue / size;
}
else
{
for(unsigned int i = 0; i < size; ++i)
medianValue += dataSet[i].first.y();
return medianValue / size;
}
}
private:
//! No copy allowed
TeAdaptativeKdTree(const TeAdaptativeKdTree& other);
//! No copy allowed
TeAdaptativeKdTree& operator=(const TeAdaptativeKdTree& other);
}; // end class TeAdaptativeKdTree
template<class KdTreeNode>
KdTreeNode* TeAdaptativeKdTree<KdTreeNode>::build(vector<pair<kdKey, kdDataItem> >& dataSet, double averageValue, const TeBox& mbr)
{
++size_;
if(dataSet.size() <= bucketSize_)
{
KdTreeNode* node = new KdTreeNode(averageValue);
node->setDiscriminator('l');
//node->setBox(mbr);
unsigned int size = dataSet.size();
for(unsigned int i = 0; i < size; ++i)
node->getData().push_back(dataSet[i].second);
return node;
}
TeBox newMbr1(mbr);
TeBox newMbr2(mbr);
char discriminator = 'x';
vector<pair<kdKey, kdDataItem> > leftDataSet;
vector<pair<kdKey, kdDataItem> > rightDataSet;
// Finds the largest dimension
if((mbr.x2_ - mbr.x1_) > (mbr.y2_ - mbr.y1_))
{
// Finds the median along "x" axis
averageValue = average(dataSet, 'x');
// Adjust box for left and right branchs
newMbr1.x2_ = averageValue;
newMbr2.x1_ = averageValue;
unsigned int size = dataSet.size();
for(unsigned int i = 0; i < size; ++ i)
{
if(dataSet[i].first.x() <= averageValue)
leftDataSet.push_back(dataSet[i]);
else
rightDataSet.push_back(dataSet[i]);
}
}
else
{
discriminator = 'y';
// Finds the median along "y" axis
averageValue = average(dataSet, 'y');
// Adjust box for left and right branchs
newMbr1.y2_ = averageValue;
newMbr2.y1_ = averageValue;
unsigned int size = dataSet.size();
for(unsigned int i = 0; i < size; ++ i)
{
if(dataSet[i].first.y() <= averageValue)
leftDataSet.push_back(dataSet[i]);
else
rightDataSet.push_back(dataSet[i]);
}
}
dataSet.clear();
KdTreeNode* node = new KdTreeNode(averageValue);
//node->setBox(mbr);
if(rightDataSet.size() == 0u) // If all coordinates have the same coordinate values, the right vector will be empty so we need stop division to
{
node->setDiscriminator('l');
//node->setBox(newMbr1);
unsigned int size = leftDataSet.size();
for(unsigned int i = 0; i < size; ++i)
node->getData().push_back(leftDataSet[i].second);
//throw;
}
else if(leftDataSet.size() == 0u) // If all coordinates have the same coordinate values, the left vector is empty, so we need to stop
{
node->setDiscriminator('l');
//node->setBox(newMbr2);
unsigned int size = rightDataSet.size();
for(unsigned int i = 0; i < size; ++i)
node->getData().push_back(rightDataSet[i].second);
//throw;
}
else
{
node->setDiscriminator(discriminator);
node->setLeft(build(leftDataSet, averageValue, newMbr1));
node->setRight(build(rightDataSet, averageValue, newMbr2));
}
return node;
}
template<class KdTreeNode>
void TeAdaptativeKdTree<KdTreeNode>::search(const TeBox& rect, vector<kdDataItem>& report) const
{
vector<KdTreeNode*> reportNodes;
search(rect, reportNodes);
unsigned int nNodes = reportNodes.size();
for(unsigned int i = 0; i < nNodes; ++i)
{
unsigned int nElements = reportNodes[i]->getData().size();
for(unsigned int j = 0; j < nElements; ++j)
{
if(TeIntersects((reportNodes[i])->getData()[j], rect))
{
report.push_back((reportNodes[i])->getData()[j]);
}
}
}
}
template<class KdTreeNode>
void TeAdaptativeKdTree<KdTreeNode>::search(const TeBox& rect, KdTreeNode* node, vector<KdTreeNode*>& report) const
{
if(node->getDiscriminator() == 'x')
{
if(node->hasLeft())
if(rect.x1_ <= node->getKey())
search(rect, node->getLeft(), report);
if(node->hasRight())
if(rect.x2_ >= node->getKey())
search(rect, node->getRight(), report);
}
else if(node->getDiscriminator() == 'y')
{
if(node->hasLeft())
if(rect.y1_ <= node->getKey())
search(rect, node->getLeft(), report);
if(node->hasRight())
if(rect.y2_ >= node->getKey())
search(rect, node->getRight(), report);
}
else
{
report.push_back(node);
}
return;
}
template<class KdTreeNode>
void TeAdaptativeKdTree<KdTreeNode>::nearestNeighborSearch(KdTreeNode* node, const kdKey& key, vector<kdDataItem>& report, vector<double>& sqrDists, TeBox& rect) const
{
if(node->getDiscriminator() == 'l')
{
update(node, key, report, sqrDists, rect); // this is a leaf node -> update list of neighbours
}
else if(node->getDiscriminator() == 'x')
{
if(key.x() <= node->getKey())
{
nearestNeighborSearch(node->getLeft(), key, report, sqrDists, rect);
if((rect.x1_ < node->getKey()) && (node->getKey() < rect.x2_))
nearestNeighborSearch(node->getRight(), key, report, sqrDists, rect);
}
else
{
nearestNeighborSearch(node->getRight(), key, report, sqrDists, rect);
if((rect.x1_ < node->getKey()) &&(node->getKey() < rect.x2_))
nearestNeighborSearch(node->getLeft(), key, report, sqrDists, rect);
}
}
else if(node->getDiscriminator() == 'y')
{
if(key.y() <= node->getKey())
{
nearestNeighborSearch(node->getLeft(), key, report, sqrDists, rect);
if((rect.y1_ < node->getKey()) &&(node->getKey() < rect.y2_ ))
nearestNeighborSearch(node->getRight(), key, report, sqrDists, rect);
}
else
{
nearestNeighborSearch(node->getRight(), key, report, sqrDists, rect);
if((rect.y1_ < node->getKey()) &&(node->getKey() < rect.y2_))
nearestNeighborSearch(node->getLeft(), key, report, sqrDists, rect);
}
}
}
template<class KdTreeNode>
void TeAdaptativeKdTree<KdTreeNode>::update(KdTreeNode* node, const kdKey& key, vector<kdDataItem>& report, vector<double>& sqrDists, TeBox& rect) const
{
// rect is the bounding box of neighbors
const unsigned int size = node->getData().size();
const unsigned int nNeighbors = report.size();
// for each element in the node, we need to search for distances less than of some one of sqrDists
for(unsigned int i = 0u; i < size; ++i)
{
double dx = (key.x() - node->getData()[i].location().x());
double dy = (key.y() - node->getData()[i].location().y());
double dkp = (dx * dx) + (dy * dy); // square distance from the key point to the node
// if the distance of "i-th" element is less than the maximum distance in the sqrDists
if(dkp < sqrDists[nNeighbors - 1])
{
// so the element must be reported
// and the srqDists vector must be rearranged
for(unsigned int j = 0u; j < nNeighbors; ++j)
{
if(dkp < sqrDists[j]) // if the position is found
{
// move the elements to the right
for(unsigned int k = nNeighbors - 1; k > j; --k)
{
report[k] = report[k - 1];
sqrDists[k] = sqrDists[k - 1];
}
// inserts the element in the report and update its distance
report[j] = node->getData()[i];
sqrDists[j] = dkp;
break;
}
}
}
}
double maxDist = sqrDists[nNeighbors - 1];
if(maxDist != TeMAXFLOAT)
{
maxDist = sqrt(maxDist);
}
rect.x1_ = key.x() - maxDist;
rect.y1_ = key.y() - maxDist;
rect.x2_ = key.x() + maxDist;
rect.y2_ = key.y() + maxDist;
}
/** @} */
}; // end namespace TeSAM
#endif // __TERRALIB_INTERNAL_KDTREE_H
|