node.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. /****************************************************************************
  2. * MODULE: R-Tree library
  3. *
  4. * AUTHOR(S): Antonin Guttman - original code
  5. * Daniel Green (green@superliminal.com) - major clean-up
  6. * and implementation of bounding spheres
  7. * Markus Metz - R*-tree
  8. *
  9. * PURPOSE: Multidimensional index
  10. *
  11. * COPYRIGHT: (C) 2009 by the GRASS Development Team
  12. *
  13. * This program is free software under the GNU General Public
  14. * License (>=v2). Read the file COPYING that comes with GRASS
  15. * for details.
  16. *****************************************************************************/
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <assert.h>
  20. #include "index.h"
  21. #include "card.h"
  22. /* rectangle distances for forced removal */
  23. struct dist
  24. {
  25. int id; /* branch id */
  26. RectReal distance; /* distance to node center */
  27. };
  28. /* Initialize one branch cell in a node. */
  29. static void RTreeInitBranch(struct Branch *b)
  30. {
  31. RTreeInitRect(&(b->rect));
  32. b->child = NULL;
  33. }
  34. /* Initialize a Node structure. */
  35. void RTreeInitNode(struct Node *n)
  36. {
  37. int i;
  38. n->count = 0;
  39. n->level = -1;
  40. for (i = 0; i < MAXCARD; i++)
  41. RTreeInitBranch(&(n->branch[i]));
  42. }
  43. /* Make a new node and initialize to have all branch cells empty. */
  44. struct Node *RTreeNewNode(struct RTree *t)
  45. {
  46. struct Node *n;
  47. n = (struct Node *)malloc((size_t) t->nodesize);
  48. assert(n);
  49. RTreeInitNode(n);
  50. return n;
  51. }
  52. void RTreeFreeNode(struct Node *n)
  53. {
  54. assert(n);
  55. free(n);
  56. }
  57. /*
  58. * Find the smallest rectangle that includes all rectangles in
  59. * branches of a node.
  60. */
  61. struct Rect RTreeNodeCover(struct Node *n, struct RTree *t)
  62. {
  63. int i, first_time = 1, maxkids;
  64. struct Rect r;
  65. assert(n);
  66. maxkids = ((n)->level > 0 ? t->nodecard : t->leafcard);
  67. RTreeInitRect(&r);
  68. for (i = 0; i < maxkids; i++)
  69. if (n->branch[i].child) {
  70. if (first_time) {
  71. r = n->branch[i].rect;
  72. first_time = 0;
  73. }
  74. else
  75. r = RTreeCombineRect(&r, &(n->branch[i].rect), t);
  76. }
  77. return r;
  78. }
  79. /*
  80. * Idea from R*-tree, modified: not overlap size but overlap number
  81. *
  82. * Pick a branch from leaf nodes (current node has level 1). Pick the
  83. * one that will result in the smallest number of overlapping siblings.
  84. * This will result in the least ambiguous node covering the new
  85. * rectangle, improving search speed.
  86. * In case of a tie, pick the one which needs the smallest increase in
  87. * area to accomodate the new rectangle, then the smallest area before,
  88. * to get the best resolution when searching.
  89. */
  90. static int RTreePickBranch1(struct Rect *r, struct Node *n, struct RTree *t)
  91. {
  92. struct Rect *rr;
  93. int i, j;
  94. RectReal increase, bestIncr = (RectReal) - 1, area, bestArea = 0;
  95. int best = 0, bestoverlap;
  96. struct Rect tmp_rect;
  97. int overlap;
  98. assert(r && n && t);
  99. bestoverlap = t->nodecard + 1;
  100. /* get the branch that will overlap with the smallest number of
  101. * sibling branches when including the new rectangle */
  102. for (i = 0; i < t->nodecard; i++) {
  103. if (n->branch[i].child) {
  104. rr = &n->branch[i].rect;
  105. tmp_rect = RTreeCombineRect(r, rr, t);
  106. area = RTreeRectSphericalVolume(rr, t);
  107. increase = RTreeRectSphericalVolume(&tmp_rect, t) - area;
  108. overlap = 0;
  109. for (j = 0; j < t->leafcard; j++) {
  110. if (j != i) {
  111. rr = &n->branch[j].rect;
  112. overlap += RTreeOverlap(&tmp_rect, rr, t);
  113. }
  114. }
  115. if (overlap < bestoverlap) {
  116. best = i;
  117. bestoverlap = overlap;
  118. bestArea = area;
  119. bestIncr = increase;
  120. }
  121. else if (overlap == bestoverlap) {
  122. /* resolve ties */
  123. if (increase < bestIncr) {
  124. best = i;
  125. bestArea = area;
  126. bestIncr = increase;
  127. }
  128. else if (increase == bestIncr && area < bestArea) {
  129. best = i;
  130. bestArea = area;
  131. }
  132. }
  133. }
  134. }
  135. return best;
  136. }
  137. /*
  138. * Pick a branch. Pick the one that will need the smallest increase
  139. * in area to accomodate the new rectangle. This will result in the
  140. * least total area for the covering rectangles in the current node.
  141. * In case of a tie, pick the one which was smaller before, to get
  142. * the best resolution when searching.
  143. */
  144. int RTreePickBranch(struct Rect *r, struct Node *n, struct RTree *t)
  145. {
  146. struct Rect *rr;
  147. int i, first_time = 1;
  148. RectReal increase, bestIncr = (RectReal) - 1, area, bestArea = 0;
  149. int best = 0;
  150. struct Rect tmp_rect;
  151. assert(r && n && t);
  152. assert((n)->level > 0); /* must not be called on leaf node */
  153. if ((n)->level == 1)
  154. return RTreePickBranch1(r, n, t);
  155. for (i = 0; i < t->nodecard; i++) {
  156. if (n->branch[i].child) {
  157. rr = &n->branch[i].rect;
  158. area = RTreeRectSphericalVolume(rr, t);
  159. tmp_rect = RTreeCombineRect(r, rr, t);
  160. increase = RTreeRectSphericalVolume(&tmp_rect, t) - area;
  161. if (increase < bestIncr || first_time) {
  162. best = i;
  163. bestArea = area;
  164. bestIncr = increase;
  165. first_time = 0;
  166. }
  167. else if (increase == bestIncr && area < bestArea) {
  168. best = i;
  169. bestArea = area;
  170. }
  171. }
  172. }
  173. return best;
  174. }
  175. /* Disconnect a dependent node. */
  176. void RTreeDisconnectBranch(struct Node *n, int i, struct RTree *t)
  177. {
  178. int maxkids;
  179. maxkids = ((n)->level > 0 ? t->nodecard : t->leafcard);
  180. assert(n && i >= 0 && i < maxkids);
  181. assert(n->branch[i].child);
  182. RTreeInitBranch(&(n->branch[i]));
  183. n->count--;
  184. }
  185. /* Destroy (free) node recursively. */
  186. /* NOTE: only needed for memory based index */
  187. void RTreeDestroyNode(struct Node *n, int nodes)
  188. {
  189. int i;
  190. if (n->level > 0) { /* it is not leaf -> destroy childs */
  191. for (i = 0; i < nodes; i++) {
  192. if (n->branch[i].child) {
  193. RTreeDestroyNode(n->branch[i].child, nodes);
  194. }
  195. }
  196. }
  197. /* Free this node */
  198. RTreeFreeNode(n);
  199. }
  200. /**********************************************************************
  201. * *
  202. * R*-tree: force remove p (currently 3) branches for reinsertion *
  203. * *
  204. **********************************************************************/
  205. /*
  206. * swap dist structs
  207. */
  208. static void RTreeSwapDist(struct dist *a, struct dist *b)
  209. {
  210. struct dist c;
  211. c = *a;
  212. *a = *b;
  213. *b = c;
  214. }
  215. /*
  216. * check if dist is sorted ascending to distance
  217. */
  218. static int RTreeDistIsSorted(struct dist *d, int first, int last)
  219. {
  220. int i;
  221. for (i = first; i < last; i++) {
  222. if (d[i].distance > d[i + 1].distance)
  223. return 0;
  224. }
  225. return 1;
  226. }
  227. /*
  228. * partition dist for quicksort on distance
  229. */
  230. static int RTreePartitionDist(struct dist *d, int first, int last)
  231. {
  232. int pivot, mid = (first + last) / 2;
  233. int larger, smaller;
  234. if (last - first == 1) { /* only two items in list */
  235. if (d[first].distance > d[last].distance) {
  236. RTreeSwapDist(&(d[first]), &(d[last]));
  237. }
  238. return last;
  239. }
  240. /* Larger of two */
  241. if (d[first].distance > d[mid].distance) {
  242. larger = pivot = first;
  243. smaller = mid;
  244. }
  245. else {
  246. larger = pivot = mid;
  247. smaller = first;
  248. }
  249. if (d[larger].distance > d[last].distance) {
  250. /* larger is largest, get the larger of smaller and last */
  251. if (d[smaller].distance > d[last].distance) {
  252. pivot = smaller;
  253. }
  254. else {
  255. pivot = last;
  256. }
  257. }
  258. if (pivot != last) {
  259. RTreeSwapDist(&(d[pivot]), &(d[last]));
  260. }
  261. pivot = first;
  262. while (first < last) {
  263. if (d[first].distance <= d[last].distance) {
  264. if (pivot != first) {
  265. RTreeSwapDist(&(d[pivot]), &(d[first]));
  266. }
  267. pivot++;
  268. }
  269. ++first;
  270. }
  271. if (pivot != last) {
  272. RTreeSwapDist(&(d[pivot]), &(d[last]));
  273. }
  274. return pivot;
  275. }
  276. /*
  277. * quicksort dist struct ascending by distance
  278. * n is last valid index
  279. */
  280. static void RTreeQuicksortDist(struct dist *d, int n)
  281. {
  282. int pivot, first, last;
  283. int s_first[MAXCARD + 1], s_last[MAXCARD + 1], stacksize;
  284. s_first[0] = 0;
  285. s_last[0] = n;
  286. stacksize = 1;
  287. /* use stack */
  288. while (stacksize) {
  289. stacksize--;
  290. first = s_first[stacksize];
  291. last = s_last[stacksize];
  292. if (first < last) {
  293. if (!RTreeDistIsSorted(d, first, last)) {
  294. pivot = RTreePartitionDist(d, first, last);
  295. s_first[stacksize] = first;
  296. s_last[stacksize] = pivot - 1;
  297. stacksize++;
  298. s_first[stacksize] = pivot + 1;
  299. s_last[stacksize] = last;
  300. stacksize++;
  301. }
  302. }
  303. }
  304. }
  305. /*
  306. * Allocate space for a branch in the list used in InsertRect to
  307. * store branches of nodes that are too full.
  308. */
  309. static struct ListBranch *RTreeNewListBranch(void)
  310. {
  311. return (struct ListBranch *)malloc(sizeof(struct ListBranch));
  312. /* return new ListBranch; */
  313. }
  314. /*
  315. * Remove branches from a node. Select the 3 branches whose rectangle
  316. * center is farthest away from node cover center.
  317. * Old node updated.
  318. */
  319. /*
  320. * Add a branch to the reinsertion list. It will later
  321. * be reinserted into the index structure.
  322. */
  323. static void RTreeReInsertBranch(struct Branch b, int level,
  324. struct ListBranch **ee)
  325. {
  326. register struct ListBranch *l;
  327. l = RTreeNewListBranch();
  328. l->b = b;
  329. l->level = level;
  330. l->next = *ee;
  331. *ee = l;
  332. }
  333. static void RTreeRemoveBranches(struct Node *n, struct Branch *b,
  334. struct ListBranch **ee, struct Rect *cover,
  335. struct RTree *t)
  336. {
  337. int i, j, maxkids;
  338. RectReal center_n[NUMDIMS], center_r, delta;
  339. struct Branch branchbuf[MAXCARD + 1];
  340. struct dist rdist[MAXCARD + 1];
  341. maxkids = t->nodecard;
  342. assert(n->count == maxkids); /* must be full */
  343. /* center coords of node cover */
  344. for (j = 0; j < t->ndims; j++) {
  345. center_n[j] = (cover->boundary[j + NUMDIMS] + cover->boundary[j]) / 2;
  346. }
  347. /* compute distances of child rectangle centers to node cover center */
  348. for (i = 0; i < maxkids; i++) {
  349. branchbuf[i] = n->branch[i];
  350. rdist[i].distance = 0;
  351. rdist[i].id = i;
  352. for (j = 0; j < t->ndims; j++) {
  353. center_r =
  354. (n->branch[i].rect.boundary[j + NUMDIMS] +
  355. n->branch[i].rect.boundary[j]) / 2;
  356. delta = center_n[j] - center_r;
  357. rdist[i].distance += delta * delta;
  358. }
  359. RTreeInitBranch(&(n->branch[i]));
  360. }
  361. /* new branch */
  362. branchbuf[maxkids] = *b;
  363. rdist[maxkids].distance = 0;
  364. rdist[maxkids].id = i;
  365. /* quicksort dist */
  366. RTreeQuicksortDist(rdist, maxkids);
  367. /* put largest three in branch list */
  368. for (i = 0; i < FORCECARD; i++) {
  369. RTreeReInsertBranch(branchbuf[rdist[maxkids - i].id], n->level, ee);
  370. }
  371. /* put remaining in node, closest to center first */
  372. for (i = 0; i < maxkids - FORCECARD + 1; i++) {
  373. n->branch[i] = branchbuf[rdist[i].id];
  374. }
  375. n->count = maxkids - FORCECARD + 1;
  376. }
  377. /*
  378. * Add a branch to a node. Split the node if necessary.
  379. * Returns 0 if node not split. Old node updated.
  380. * Returns 1 if node split, sets *new_node to address of new node.
  381. * Old node updated, becomes one of two.
  382. */
  383. int RTreeAddBranch(struct Branch *b, struct Node *n,
  384. struct Node **new_node, struct ListBranch **ee,
  385. struct Rect *cover, int *overflow, struct RTree *t)
  386. {
  387. int i, maxkids;
  388. assert(b);
  389. assert(n);
  390. maxkids = ((n)->level > 0 ? t->nodecard : t->leafcard);
  391. if (n->count < maxkids) { /* split won't be necessary */
  392. for (i = 0; i < maxkids; i++) { /* find empty branch */
  393. if (n->branch[i].child == 0) {
  394. n->branch[i] = *b;
  395. n->count++;
  396. break;
  397. }
  398. }
  399. return 0;
  400. }
  401. else {
  402. if (n->level < t->n_levels && overflow[n->level]) {
  403. /* R*-tree forced reinsert */
  404. RTreeRemoveBranches(n, b, ee, cover, t);
  405. overflow[n->level] = 0;
  406. return 2;
  407. }
  408. else {
  409. *new_node = RTreeNewNode(t);
  410. RTreeSplitNode(n, b, *new_node, t);
  411. return 1;
  412. }
  413. }
  414. }
  415. /*
  416. * for debugging only: print items to stdout
  417. */
  418. void RTreeTabIn(int depth)
  419. {
  420. int i;
  421. for (i = 0; i < depth; i++)
  422. putchar('\t');
  423. }
  424. static void RTreePrintBranch(struct Branch *b, int depth, struct RTree *t)
  425. {
  426. RTreePrintRect(&(b->rect), depth);
  427. RTreePrintNode(b->child, depth, t);
  428. }
  429. /* Print out the data in a node. */
  430. void RTreePrintNode(struct Node *n, int depth, struct RTree *t)
  431. {
  432. int i, maxkids;
  433. RTreeTabIn(depth);
  434. maxkids = (n->level > 0 ? t->nodecard : t->leafcard);
  435. fprintf(stdout, "node");
  436. if (n->level == 0)
  437. fprintf(stdout, " LEAF");
  438. else if (n->level > 0)
  439. fprintf(stdout, " NONLEAF");
  440. else
  441. fprintf(stdout, " TYPE=?");
  442. fprintf(stdout, " level=%d count=%d", n->level, n->count);
  443. for (i = 0; i < maxkids; i++) {
  444. if (n->level == 0) {
  445. RTreeTabIn(depth);
  446. RTreePrintRect(&(n->branch[i].rect), depth);
  447. fprintf(stdout, "\t%d: data id = %o\n", i,
  448. (unsigned)n->branch[i].child);
  449. }
  450. else {
  451. RTreeTabIn(depth);
  452. fprintf(stdout, "branch %d\n", i);
  453. RTreePrintBranch(&(n->branch[i]), depth + 1, t);
  454. }
  455. }
  456. }