node.c 14 KB

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