node.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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 RTree_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 RTree_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 RTree_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 RTree_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 RTree_Node *RTreeNewNode(struct RTree *t, int level)
  62. {
  63. struct RTree_Node *n;
  64. n = (struct RTree_Node *)malloc((size_t) t->nodesize);
  65. assert(n);
  66. RTreeInitNode(n, NODETYPE(level, t->fd));
  67. return n;
  68. }
  69. void RTreeFreeNode(struct RTree_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 RTree_Rect RTreeNodeCover(struct RTree_Node *n, struct RTree *t)
  79. {
  80. int i, first_time = 1;
  81. struct RTree_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 RTree_Rect *r, struct RTree_Node *n, struct RTree *t)
  121. {
  122. struct RTree_Rect *rr;
  123. int i, j;
  124. RectReal increase, bestIncr = -1, area, bestArea = 0;
  125. int best = 0, bestoverlap;
  126. struct RTree_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 RTree_Rect *r, struct RTree_Node *n, struct RTree *t)
  174. {
  175. struct RTree_Rect *rr;
  176. int i, first_time = 1;
  177. RectReal increase, bestIncr = (RectReal) -1, area, bestArea = 0;
  178. int best = 0;
  179. struct RTree_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 RTree_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 RTree_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. return;
  236. }
  237. /****************************************************************
  238. * *
  239. * R*-tree: force remove FORCECARD branches for reinsertion *
  240. * *
  241. ****************************************************************/
  242. /*
  243. * swap dist structs
  244. */
  245. static void RTreeSwapDist(struct dist *a, struct dist *b)
  246. {
  247. struct dist c;
  248. c = *a;
  249. *a = *b;
  250. *b = c;
  251. }
  252. /*
  253. * check if dist is sorted ascending to distance
  254. */
  255. static int RTreeDistIsSorted(struct dist *d, int first, int last)
  256. {
  257. int i;
  258. for (i = first; i < last; i++) {
  259. if (d[i].distance > d[i + 1].distance)
  260. return 0;
  261. }
  262. return 1;
  263. }
  264. /*
  265. * partition dist for quicksort on distance
  266. */
  267. static int RTreePartitionDist(struct dist *d, int first, int last)
  268. {
  269. int pivot, mid = (first + last) / 2;
  270. int larger, smaller;
  271. if (last - first == 1) { /* only two items in list */
  272. if (d[first].distance > d[last].distance) {
  273. RTreeSwapDist(&(d[first]), &(d[last]));
  274. }
  275. return last;
  276. }
  277. /* Larger of two */
  278. if (d[first].distance > d[mid].distance) {
  279. larger = pivot = first;
  280. smaller = mid;
  281. }
  282. else {
  283. larger = pivot = mid;
  284. smaller = first;
  285. }
  286. if (d[larger].distance > d[last].distance) {
  287. /* larger is largest, get the larger of smaller and last */
  288. if (d[smaller].distance > d[last].distance) {
  289. pivot = smaller;
  290. }
  291. else {
  292. pivot = last;
  293. }
  294. }
  295. if (pivot != last) {
  296. RTreeSwapDist(&(d[pivot]), &(d[last]));
  297. }
  298. pivot = first;
  299. while (first < last) {
  300. if (d[first].distance <= d[last].distance) {
  301. if (pivot != first) {
  302. RTreeSwapDist(&(d[pivot]), &(d[first]));
  303. }
  304. pivot++;
  305. }
  306. ++first;
  307. }
  308. if (pivot != last) {
  309. RTreeSwapDist(&(d[pivot]), &(d[last]));
  310. }
  311. return pivot;
  312. }
  313. /*
  314. * quicksort dist struct ascending by distance
  315. * n is last valid index
  316. */
  317. static void RTreeQuicksortDist(struct dist *d, int n)
  318. {
  319. int pivot, first, last;
  320. int s_first[MAXCARD + 1], s_last[MAXCARD + 1], stacksize;
  321. s_first[0] = 0;
  322. s_last[0] = n;
  323. stacksize = 1;
  324. /* use stack */
  325. while (stacksize) {
  326. stacksize--;
  327. first = s_first[stacksize];
  328. last = s_last[stacksize];
  329. if (first < last) {
  330. if (!RTreeDistIsSorted(d, first, last)) {
  331. pivot = RTreePartitionDist(d, first, last);
  332. s_first[stacksize] = first;
  333. s_last[stacksize] = pivot - 1;
  334. stacksize++;
  335. s_first[stacksize] = pivot + 1;
  336. s_last[stacksize] = last;
  337. stacksize++;
  338. }
  339. }
  340. }
  341. }
  342. /*
  343. * Allocate space for a branch in the list used in InsertRect to
  344. * store branches of nodes that are too full.
  345. */
  346. static struct RTree_ListBranch *RTreeNewListBranch(void)
  347. {
  348. return (struct RTree_ListBranch *)malloc(sizeof(struct RTree_ListBranch));
  349. }
  350. /*
  351. * Add a branch to the reinsertion list. It will later
  352. * be reinserted into the index structure.
  353. */
  354. static void RTreeReInsertBranch(struct RTree_Branch b, int level,
  355. struct RTree_ListBranch **ee)
  356. {
  357. register struct RTree_ListBranch *l;
  358. l = RTreeNewListBranch();
  359. l->b = b;
  360. l->level = level;
  361. l->next = *ee;
  362. *ee = l;
  363. }
  364. /*
  365. * Remove branches from a node. Select the 2 branches whose rectangle
  366. * center is farthest away from node cover center.
  367. * Old node updated.
  368. */
  369. static void RTreeRemoveBranches(struct RTree_Node *n, struct RTree_Branch *b,
  370. struct RTree_ListBranch **ee, struct RTree_Rect *cover,
  371. struct RTree *t)
  372. {
  373. int i, j, maxkids, type;
  374. RectReal center_n[NUMDIMS], center_r, delta;
  375. struct RTree_Branch branchbuf[MAXCARD + 1];
  376. struct dist rdist[MAXCARD + 1];
  377. struct RTree_Rect new_cover;
  378. assert(cover);
  379. maxkids = MAXKIDS((n)->level, t);
  380. type = NODETYPE((n)->level, t->fd);
  381. assert(n->count == maxkids); /* must be full */
  382. new_cover = RTreeCombineRect(cover, &(b->rect), t);
  383. /* center coords of node cover */
  384. for (j = 0; j < t->ndims; j++) {
  385. center_n[j] = (new_cover.boundary[j + NUMDIMS] + new_cover.boundary[j]) / 2;
  386. }
  387. /* compute distances of child rectangle centers to node cover center */
  388. for (i = 0; i < maxkids; i++) {
  389. branchbuf[i] = n->branch[i];
  390. rdist[i].distance = 0;
  391. rdist[i].id = i;
  392. for (j = 0; j < t->ndims; j++) {
  393. center_r =
  394. (branchbuf[i].rect.boundary[j + NUMDIMS] +
  395. branchbuf[i].rect.boundary[j]) / 2;
  396. delta = center_n[j] - center_r;
  397. rdist[i].distance += delta * delta;
  398. }
  399. RTreeInitBranch[type](&(n->branch[i]));
  400. }
  401. /* new branch */
  402. branchbuf[maxkids] = *b;
  403. rdist[maxkids].distance = 0;
  404. for (j = 0; j < t->ndims; j++) {
  405. center_r =
  406. (b->rect.boundary[j + NUMDIMS] +
  407. b->rect.boundary[j]) / 2;
  408. delta = center_n[j] - center_r;
  409. rdist[maxkids].distance += delta * delta;
  410. }
  411. rdist[maxkids].id = maxkids;
  412. /* quicksort dist */
  413. RTreeQuicksortDist(rdist, maxkids);
  414. /* put largest three in branch list, farthest from center first */
  415. for (i = 0; i < FORCECARD; i++) {
  416. RTreeReInsertBranch(branchbuf[rdist[maxkids - i].id], n->level, ee);
  417. }
  418. /* put remaining in node, closest to center first */
  419. for (i = 0; i < maxkids - FORCECARD + 1; i++) {
  420. n->branch[i] = branchbuf[rdist[i].id];
  421. }
  422. n->count = maxkids - FORCECARD + 1;
  423. }
  424. /*
  425. * Add a branch to a node. Split the node if necessary.
  426. * Returns 0 if node not split. Old node updated.
  427. * Returns 1 if node split, sets *new_node to address of new node.
  428. * Old node updated, becomes one of two.
  429. * Returns 2 if branches were removed for forced reinsertion
  430. */
  431. int RTreeAddBranch(struct RTree_Branch *b, struct RTree_Node *n,
  432. struct RTree_Node **newnode, struct RTree_ListBranch **ee,
  433. struct RTree_Rect *cover, int *overflow, struct RTree *t)
  434. {
  435. int i, maxkids;
  436. maxkids = MAXKIDS((n)->level, t);
  437. if (n->count < maxkids) { /* split won't be necessary */
  438. if ((n)->level > 0) { /* internal node */
  439. for (i = 0; i < maxkids; i++) { /* find empty branch */
  440. if (!t->valid_child(&(n->branch[i].child))) {
  441. n->branch[i] = *b;
  442. n->count++;
  443. break;
  444. }
  445. }
  446. return 0;
  447. }
  448. else if ((n)->level == 0) { /* leaf */
  449. for (i = 0; i < maxkids; i++) { /* find empty branch */
  450. if (n->branch[i].child.id == 0) {
  451. n->branch[i] = *b;
  452. n->count++;
  453. break;
  454. }
  455. }
  456. return 0;
  457. }
  458. }
  459. else {
  460. if (n->level < t->rootlevel && overflow[n->level]) {
  461. /* R*-tree forced reinsert */
  462. RTreeRemoveBranches(n, b, ee, cover, t);
  463. overflow[n->level] = 0;
  464. return 2;
  465. }
  466. else {
  467. if (t->fd > -1)
  468. RTreeInitNode(*newnode, NODETYPE(n->level, t->fd));
  469. else
  470. *newnode = RTreeNewNode(t, (n)->level);
  471. RTreeSplitNode(n, b, *newnode, t);
  472. return 1;
  473. }
  474. }
  475. /* should not be reached */
  476. assert(0);
  477. return -1;
  478. }
  479. /*
  480. * for debugging only: print items to stdout
  481. */
  482. void RTreeTabIn(int depth)
  483. {
  484. int i;
  485. for (i = 0; i < depth; i++)
  486. putchar('\t');
  487. }
  488. static void RTreePrintBranch(struct RTree_Branch *b, int depth, struct RTree *t)
  489. {
  490. RTreePrintRect(&(b->rect), depth);
  491. RTreePrintNode(b->child.ptr, depth, t);
  492. }
  493. /* Print out the data in a node. */
  494. void RTreePrintNode(struct RTree_Node *n, int depth, struct RTree *t)
  495. {
  496. int i, maxkids;
  497. RTreeTabIn(depth);
  498. maxkids = (n->level > 0 ? t->nodecard : t->leafcard);
  499. fprintf(stdout, "node");
  500. if (n->level == 0)
  501. fprintf(stdout, " LEAF");
  502. else if (n->level > 0)
  503. fprintf(stdout, " NONLEAF");
  504. else
  505. fprintf(stdout, " TYPE=?");
  506. fprintf(stdout, " level=%d count=%d", n->level, n->count);
  507. for (i = 0; i < maxkids; i++) {
  508. if (n->level == 0) {
  509. RTreeTabIn(depth);
  510. RTreePrintRect(&(n->branch[i].rect), depth);
  511. fprintf(stdout, "\t%d: data id = %d\n", i,
  512. n->branch[i].child.id);
  513. }
  514. else {
  515. RTreeTabIn(depth);
  516. fprintf(stdout, "branch %d\n", i);
  517. RTreePrintBranch(&(n->branch[i]), depth + 1, t);
  518. }
  519. }
  520. }