kdtree.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. /*!
  2. * \file kdtree.c
  3. *
  4. * \brief binary search tree
  5. *
  6. * Dynamic balanced k-d tree implementation
  7. *
  8. * (C) 2014 by the GRASS Development Team
  9. *
  10. * This program is free software under the GNU General Public License
  11. * (>=v2). Read the file COPYING that comes with GRASS for details.
  12. *
  13. * \author Markus Metz
  14. */
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <math.h>
  18. #include <grass/gis.h>
  19. #include <grass/glocale.h>
  20. #include "kdtree.h"
  21. #define KD_BTOL 7
  22. #ifdef KD_DEBUG
  23. #undef KD_DEBUG
  24. #endif
  25. static int rcalls = 0;
  26. static int rcallsmax = 0;
  27. static struct kdnode *kdtree_insert2(struct kdtree *, struct kdnode *,
  28. struct kdnode *, int, int);
  29. static int kdtree_replace(struct kdtree *, struct kdnode *);
  30. static int kdtree_balance(struct kdtree *, struct kdnode *, int);
  31. static int kdtree_first(struct kdtrav *, double *, int *);
  32. static int kdtree_next(struct kdtrav *, double *, int *);
  33. static int cmp(struct kdnode *a, struct kdnode *b, int p)
  34. {
  35. if (a->c[p] < b->c[p])
  36. return -1;
  37. if (a->c[p] > b->c[p])
  38. return 1;
  39. return (a->uid < b->uid ? -1 : a->uid > b->uid);
  40. }
  41. static int cmpc(struct kdnode *a, struct kdnode *b, struct kdtree *t)
  42. {
  43. int i;
  44. for (i = 0; i < t->ndims; i++) {
  45. if (a->c[i] != b->c[i]) {
  46. return 1;
  47. }
  48. }
  49. return 0;
  50. }
  51. static struct kdnode *kdtree_newnode(struct kdtree *t)
  52. {
  53. struct kdnode *n = G_malloc(sizeof(struct kdnode));
  54. n->c = G_malloc(t->ndims * sizeof(double));
  55. n->dim = 0;
  56. n->depth = 0;
  57. n->balance = 0;
  58. n->uid = 0;
  59. n->child[0] = NULL;
  60. n->child[1] = NULL;
  61. return n;
  62. }
  63. static void kdtree_free_node(struct kdnode *n)
  64. {
  65. G_free(n->c);
  66. G_free(n);
  67. }
  68. static void kdtree_update_node(struct kdtree *t, struct kdnode *n)
  69. {
  70. int ld, rd, btol;
  71. ld = (!n->child[0] ? -1 : n->child[0]->depth);
  72. rd = (!n->child[1] ? -1 : n->child[1]->depth);
  73. n->depth = MAX(ld, rd) + 1;
  74. n->balance = 0;
  75. /* set balance flag if any of the node's subtrees needs balancing
  76. * or if the node itself needs balancing */
  77. if ((n->child[0] && n->child[0]->balance) ||
  78. (n->child[1] && n->child[1]->balance)) {
  79. n->balance = 1;
  80. return;
  81. }
  82. btol = t->btol;
  83. if (!n->child[0] || !n->child[1])
  84. btol = 2;
  85. if (ld > rd + btol || rd > ld + btol)
  86. n->balance = 1;
  87. }
  88. /* create a new k-d tree with ndims dimensions,
  89. * optionally set balancing tolerance */
  90. struct kdtree *kdtree_create(char ndims, int *btol)
  91. {
  92. int i;
  93. struct kdtree *t;
  94. t = G_malloc(sizeof(struct kdtree));
  95. t->ndims = ndims;
  96. t->csize = ndims * sizeof(double);
  97. t->btol = KD_BTOL;
  98. if (btol) {
  99. t->btol = *btol;
  100. if (t->btol < 2)
  101. t->btol = 2;
  102. }
  103. t->nextdim = G_malloc(ndims * sizeof(char));
  104. for (i = 0; i < ndims - 1; i++)
  105. t->nextdim[i] = i + 1;
  106. t->nextdim[ndims - 1] = 0;
  107. t->count = 0;
  108. t->root = NULL;
  109. return t;
  110. }
  111. /* clear the tree, removing all entries */
  112. void kdtree_clear(struct kdtree *t)
  113. {
  114. struct kdnode *it;
  115. struct kdnode *save = t->root;
  116. /*
  117. Rotate away the left links so that
  118. we can treat this like the destruction
  119. of a linked list
  120. */
  121. while((it = save) != NULL) {
  122. if (it->child[0] == NULL) {
  123. /* No left links, just kill the node and move on */
  124. save = it->child[1];
  125. kdtree_free_node(it);
  126. it = NULL;
  127. }
  128. else {
  129. /* Rotate away the left link and check again */
  130. save = it->child[0];
  131. it->child[0] = save->child[1];
  132. save->child[1] = it;
  133. }
  134. }
  135. t->root = NULL;
  136. }
  137. /* destroy the tree */
  138. void kdtree_destroy(struct kdtree *t)
  139. {
  140. /* remove all entries */
  141. kdtree_clear(t);
  142. G_free(t->nextdim);
  143. G_free(t);
  144. t = NULL;
  145. }
  146. /* insert an item (coordinates c and uid) into the k-d tree
  147. * dc == 1: allow duplicate coordinates */
  148. int kdtree_insert(struct kdtree *t, double *c, int uid, int dc)
  149. {
  150. struct kdnode *nnew;
  151. size_t count = t->count;
  152. nnew = kdtree_newnode(t);
  153. memcpy(nnew->c, c, t->csize);
  154. nnew->uid = uid;
  155. t->root = kdtree_insert2(t, t->root, nnew, 1, dc);
  156. /* print depth of recursion
  157. * recursively called fns are insert2, balance, and replace */
  158. /*
  159. if (rcallsmax > 1)
  160. fprintf(stdout, "%d\n", rcallsmax);
  161. */
  162. return count < t->count;
  163. }
  164. /* remove an item from the k-d tree
  165. * coordinates c and uid must match */
  166. int kdtree_remove(struct kdtree *t, double *c, int uid)
  167. {
  168. struct kdnode sn, *n;
  169. struct kdstack {
  170. struct kdnode *n;
  171. int dir;
  172. } s[256];
  173. int top;
  174. int dir, found;
  175. int balance, bmode;
  176. sn.c = c;
  177. sn.uid = uid;
  178. /* find sn node */
  179. top = 0;
  180. s[top].n = t->root;
  181. dir = 1;
  182. found = 0;
  183. while (!found) {
  184. n = s[top].n;
  185. found = (!cmpc(&sn, n, t) && sn.uid == n->uid);
  186. if (!found) {
  187. dir = cmp(&sn, n, n->dim) > 0;
  188. s[top].dir = dir;
  189. top++;
  190. s[top].n = n->child[dir];
  191. if (!s[top].n) {
  192. G_warning("Node does not exist");
  193. return 0;
  194. }
  195. }
  196. }
  197. if (s[top].n->depth == 0) {
  198. kdtree_free_node(s[top].n);
  199. s[top].n = NULL;
  200. if (top) {
  201. top--;
  202. n = s[top].n;
  203. dir = s[top].dir;
  204. n->child[dir] = NULL;
  205. /* update node */
  206. kdtree_update_node(t, n);
  207. }
  208. else {
  209. t->root = NULL;
  210. return 1;
  211. }
  212. }
  213. else
  214. kdtree_replace(t, s[top].n);
  215. while (top) {
  216. top--;
  217. n = s[top].n;
  218. /* update node */
  219. kdtree_update_node(t, n);
  220. }
  221. balance = 1;
  222. bmode = 1;
  223. if (balance) {
  224. struct kdnode *r;
  225. int iter, bmode2;
  226. /* fix any inconsistencies in the (sub-)tree */
  227. iter = 0;
  228. bmode2 = 0;
  229. top = 0;
  230. r = t->root;
  231. s[top].n = r;
  232. while (top >= 0) {
  233. n = s[top].n;
  234. /* top-down balancing
  235. * slower but more compact */
  236. if (!bmode2) {
  237. while (kdtree_balance(t, n, bmode));
  238. }
  239. /* go down */
  240. if (n->child[0] && n->child[0]->balance) {
  241. dir = 0;
  242. top++;
  243. s[top].n = n->child[dir];
  244. }
  245. else if (n->child[1] && n->child[1]->balance) {
  246. dir = 1;
  247. top++;
  248. s[top].n = n->child[dir];
  249. }
  250. /* go back up */
  251. else {
  252. /* bottom-up balancing
  253. * faster but less compact */
  254. kdtree_update_node(t, n);
  255. if (bmode2) {
  256. while (kdtree_balance(t, n, bmode));
  257. }
  258. top--;
  259. if (top >= 0) {
  260. kdtree_update_node(t, s[top].n);
  261. }
  262. if (!bmode2 && top == 0) {
  263. iter++;
  264. if (iter == 2) {
  265. /* the top node has been visited twice,
  266. * switch from top-down to bottom-up balancing */
  267. iter = 0;
  268. bmode2 = 1;
  269. }
  270. }
  271. }
  272. }
  273. }
  274. return 1;
  275. }
  276. /* k-d tree optimization, only useful if the tree will be used heavily
  277. * (more searches than items in the tree)
  278. * level 0 = a bit, 1 = more, 2 = a lot */
  279. void kdtree_optimize(struct kdtree *t, int level)
  280. {
  281. struct kdnode *n, *n2;
  282. struct kdstack {
  283. struct kdnode *n;
  284. int dir;
  285. char v;
  286. } s[256];
  287. int dir;
  288. int top;
  289. int ld, rd;
  290. int diffl, diffr;
  291. int nbal;
  292. if (!t->root)
  293. return;
  294. G_debug(1, "k-d tree optimization for %zd items, tree depth %d",
  295. t->count, t->root->depth);
  296. nbal = 0;
  297. top = 0;
  298. s[top].n = t->root;
  299. while (s[top].n) {
  300. n = s[top].n;
  301. ld = (!n->child[0] ? -1 : n->child[0]->depth);
  302. rd = (!n->child[1] ? -1 : n->child[1]->depth);
  303. if (ld < rd)
  304. while (kdtree_balance(t, n->child[0], level));
  305. else if (ld > rd)
  306. while (kdtree_balance(t, n->child[1], level));
  307. ld = (!n->child[0] ? -1 : n->child[0]->depth);
  308. rd = (!n->child[1] ? -1 : n->child[1]->depth);
  309. n->depth = MAX(ld, rd) + 1;
  310. dir = (rd > ld);
  311. top++;
  312. s[top].n = n->child[dir];
  313. }
  314. while (top) {
  315. top--;
  316. n = s[top].n;
  317. /* balance node */
  318. while (kdtree_balance(t, n, level)) {
  319. nbal++;
  320. }
  321. while (kdtree_balance(t, n->child[0], level));
  322. while (kdtree_balance(t, n->child[1], level));
  323. ld = (!n->child[0] ? -1 : n->child[0]->depth);
  324. rd = (!n->child[1] ? -1 : n->child[1]->depth);
  325. n->depth = MAX(ld, rd) + 1;
  326. while (kdtree_balance(t, n, level)) {
  327. nbal++;
  328. }
  329. }
  330. while (s[top].n) {
  331. n = s[top].n;
  332. /* balance node */
  333. while (kdtree_balance(t, n, level)) {
  334. nbal++;
  335. }
  336. while (kdtree_balance(t, n->child[0], level));
  337. while (kdtree_balance(t, n->child[1], level));
  338. ld = (!n->child[0] ? -1 : n->child[0]->depth);
  339. rd = (!n->child[1] ? -1 : n->child[1]->depth);
  340. n->depth = MAX(ld, rd) + 1;
  341. while (kdtree_balance(t, n, level)) {
  342. nbal++;
  343. }
  344. ld = (!n->child[0] ? -1 : n->child[0]->depth);
  345. rd = (!n->child[1] ? -1 : n->child[1]->depth);
  346. dir = (rd > ld);
  347. top++;
  348. s[top].n = n->child[dir];
  349. }
  350. while (top) {
  351. top--;
  352. n = s[top].n;
  353. /* update node depth */
  354. ld = (!n->child[0] ? -1 : n->child[0]->depth);
  355. rd = (!n->child[1] ? -1 : n->child[1]->depth);
  356. n->depth = MAX(ld, rd) + 1;
  357. }
  358. if (level) {
  359. top = 0;
  360. s[top].n = t->root;
  361. while (s[top].n) {
  362. n = s[top].n;
  363. /* balance node */
  364. while (kdtree_balance(t, n, level)) {
  365. nbal++;
  366. }
  367. while (kdtree_balance(t, n->child[0], level));
  368. while (kdtree_balance(t, n->child[1], level));
  369. ld = (!n->child[0] ? -1 : n->child[0]->depth);
  370. rd = (!n->child[1] ? -1 : n->child[1]->depth);
  371. n->depth = MAX(ld, rd) + 1;
  372. while (kdtree_balance(t, n, level)) {
  373. nbal++;
  374. }
  375. diffl = diffr = -1;
  376. if (n->child[0]) {
  377. n2 = n->child[0];
  378. ld = (!n2->child[0] ? -1 : n2->child[0]->depth);
  379. rd = (!n2->child[1] ? -1 : n2->child[1]->depth);
  380. diffl = ld - rd;
  381. if (diffl < 0)
  382. diffl = -diffl;
  383. }
  384. if (n->child[1]) {
  385. n2 = n->child[1];
  386. ld = (!n2->child[0] ? -1 : n2->child[0]->depth);
  387. rd = (!n2->child[1] ? -1 : n2->child[1]->depth);
  388. diffr = ld - rd;
  389. if (diffr < 0)
  390. diffr = -diffr;
  391. }
  392. dir = (diffr > diffl);
  393. top++;
  394. s[top].n = n->child[dir];
  395. }
  396. while (top) {
  397. top--;
  398. n = s[top].n;
  399. /* update node depth */
  400. ld = (!n->child[0] ? -1 : n->child[0]->depth);
  401. rd = (!n->child[1] ? -1 : n->child[1]->depth);
  402. n->depth = MAX(ld, rd) + 1;
  403. }
  404. }
  405. G_debug(1, "k-d tree optimization: %d times balanced, new depth %d",
  406. nbal, t->root->depth);
  407. return;
  408. }
  409. /* find k nearest neighbors
  410. * results are stored in uid (uids) and d (squared distances)
  411. * optionally an uid to be skipped can be given
  412. * useful when searching for the nearest neighbors of an item
  413. * that is also in the tree */
  414. int kdtree_knn(struct kdtree *t, double *c, int *uid, double *d, int k, int *skip)
  415. {
  416. int i, found;
  417. double diff, dist, maxdist;
  418. struct kdnode sn, *n;
  419. struct kdstack {
  420. struct kdnode *n;
  421. int dir;
  422. char v;
  423. } s[256];
  424. int dir;
  425. int top;
  426. if (!t->root)
  427. return 0;
  428. sn.c = c;
  429. sn.uid = (int)0x80000000;
  430. if (skip)
  431. sn.uid = *skip;
  432. maxdist = 1.0 / 0.0;
  433. found = 0;
  434. /* go down */
  435. top = 0;
  436. s[top].n = t->root;
  437. while (s[top].n) {
  438. n = s[top].n;
  439. dir = cmp(&sn, n, n->dim) > 0;
  440. s[top].dir = dir;
  441. s[top].v = 0;
  442. top++;
  443. s[top].n = n->child[dir];
  444. }
  445. /* go back up */
  446. while (top) {
  447. top--;
  448. if (!s[top].v) {
  449. s[top].v = 1;
  450. n = s[top].n;
  451. if (n->uid != sn.uid) {
  452. if (found < k) {
  453. dist = 0.0;
  454. i = t->ndims - 1;
  455. do {
  456. diff = sn.c[i] - n->c[i];
  457. dist += diff * diff;
  458. } while (i--);
  459. i = found;
  460. while (i > 0 && d[i - 1] > dist) {
  461. d[i] = d[i - 1];
  462. uid[i] = uid[i - 1];
  463. i--;
  464. }
  465. if (i < found && d[i] == dist && uid[i] == n->uid)
  466. G_fatal_error("knn: inserting duplicate");
  467. d[i] = dist;
  468. uid[i] = n->uid;
  469. maxdist = d[found];
  470. found++;
  471. }
  472. else {
  473. dist = 0.0;
  474. i = t->ndims - 1;
  475. do {
  476. diff = sn.c[i] - n->c[i];
  477. dist += diff * diff;
  478. } while (i-- && dist <= maxdist);
  479. if (dist < maxdist) {
  480. i = k - 1;
  481. while (i > 0 && d[i - 1] > dist) {
  482. d[i] = d[i - 1];
  483. uid[i] = uid[i - 1];
  484. i--;
  485. }
  486. if (d[i] == dist && uid[i] == n->uid)
  487. G_fatal_error("knn: inserting duplicate");
  488. d[i] = dist;
  489. uid[i] = n->uid;
  490. maxdist = d[k - 1];
  491. }
  492. }
  493. if (found == k && maxdist == 0.0)
  494. break;
  495. }
  496. /* look on the other side ? */
  497. dir = s[top].dir;
  498. diff = sn.c[(int)n->dim] - n->c[(int)n->dim];
  499. dist = diff * diff;
  500. if (dist <= maxdist) {
  501. /* go down the other side */
  502. top++;
  503. s[top].n = n->child[!dir];
  504. while (s[top].n) {
  505. n = s[top].n;
  506. dir = cmp(&sn, n, n->dim) > 0;
  507. s[top].dir = dir;
  508. s[top].v = 0;
  509. top++;
  510. s[top].n = n->child[dir];
  511. }
  512. }
  513. }
  514. }
  515. return found;
  516. }
  517. /* find all nearest neighbors within distance aka radius search
  518. * results are stored in puid (uids) and pd (squared distances)
  519. * memory is allocated as needed, the calling fn must free the memory
  520. * optionally an uid to be skipped can be given */
  521. int kdtree_dnn(struct kdtree *t, double *c, int **puid, double **pd,
  522. double maxdist, int *skip)
  523. {
  524. int i, k, found;
  525. double diff, dist;
  526. struct kdnode sn, *n;
  527. struct kdstack {
  528. struct kdnode *n;
  529. int dir;
  530. char v;
  531. } s[256];
  532. int dir;
  533. int top;
  534. int *uid;
  535. double *d, maxdistsq;
  536. if (!t->root)
  537. return 0;
  538. sn.c = c;
  539. sn.uid = (int)0x80000000;
  540. if (skip)
  541. sn.uid = *skip;
  542. *pd = NULL;
  543. *puid = NULL;
  544. k = 0;
  545. uid = NULL;
  546. d = NULL;
  547. found = 0;
  548. maxdistsq = maxdist * maxdist;
  549. /* go down */
  550. top = 0;
  551. s[top].n = t->root;
  552. while (s[top].n) {
  553. n = s[top].n;
  554. dir = cmp(&sn, n, n->dim) > 0;
  555. s[top].dir = dir;
  556. s[top].v = 0;
  557. top++;
  558. s[top].n = n->child[dir];
  559. }
  560. /* go back up */
  561. while (top) {
  562. top--;
  563. if (!s[top].v) {
  564. s[top].v = 1;
  565. n = s[top].n;
  566. if (n->uid != sn.uid) {
  567. dist = 0;
  568. i = t->ndims - 1;
  569. do {
  570. diff = sn.c[i] - n->c[i];
  571. dist += diff * diff;
  572. } while (i-- && dist <= maxdistsq);
  573. if (dist <= maxdistsq) {
  574. if (found + 1 >= k) {
  575. k = found + 10;
  576. uid = G_realloc(uid, k * sizeof(int));
  577. d = G_realloc(d, k * sizeof(double));
  578. }
  579. i = found;
  580. while (i > 0 && d[i - 1] > dist) {
  581. d[i] = d[i - 1];
  582. uid[i] = uid[i - 1];
  583. i--;
  584. }
  585. if (i < found && d[i] == dist && uid[i] == n->uid)
  586. G_fatal_error("dnn: inserting duplicate");
  587. d[i] = dist;
  588. uid[i] = n->uid;
  589. found++;
  590. }
  591. }
  592. /* look on the other side ? */
  593. dir = s[top].dir;
  594. diff = fabs(sn.c[(int)n->dim] - n->c[(int)n->dim]);
  595. if (diff <= maxdist) {
  596. /* go down the other side */
  597. top++;
  598. s[top].n = n->child[!dir];
  599. while (s[top].n) {
  600. n = s[top].n;
  601. dir = cmp(&sn, n, n->dim) > 0;
  602. s[top].dir = dir;
  603. s[top].v = 0;
  604. top++;
  605. s[top].n = n->child[dir];
  606. }
  607. }
  608. }
  609. }
  610. *pd = d;
  611. *puid = uid;
  612. return found;
  613. }
  614. /* find all nearest neighbors within range aka box search
  615. * the range is specified with min and max for each dimension as
  616. * (min1, min2, ..., minn, max1, max2, ..., maxn)
  617. * results are stored in puid (uids)
  618. * memory is allocated as needed, the calling fn must free the memory
  619. * optionally an uid to be skipped can be given */
  620. int kdtree_rnn(struct kdtree *t, double *c, int **puid, int *skip)
  621. {
  622. int i, k, found, inside;
  623. struct kdnode sn, *n;
  624. struct kdstack {
  625. struct kdnode *n;
  626. int dir;
  627. char v;
  628. } s[256];
  629. int dir;
  630. int top;
  631. int *uid;
  632. if (!t->root)
  633. return 0;
  634. sn.c = c;
  635. sn.uid = (int)0x80000000;
  636. if (skip)
  637. sn.uid = *skip;
  638. *puid = NULL;
  639. k = 0;
  640. uid = NULL;
  641. found = 0;
  642. /* go down */
  643. top = 0;
  644. s[top].n = t->root;
  645. while (s[top].n) {
  646. n = s[top].n;
  647. dir = cmp(&sn, n, n->dim) > 0;
  648. s[top].dir = dir;
  649. s[top].v = 0;
  650. top++;
  651. s[top].n = n->child[dir];
  652. }
  653. /* go back up */
  654. while (top) {
  655. top--;
  656. if (!s[top].v) {
  657. s[top].v = 1;
  658. n = s[top].n;
  659. if (n->uid != sn.uid) {
  660. inside = 1;
  661. for (i = 0; i < t->ndims; i++) {
  662. if (n->c[i] < sn.c[i] || n->c[i] > sn.c[i + t->ndims]) {
  663. inside = 0;
  664. break;
  665. }
  666. }
  667. if (inside) {
  668. if (found + 1 >= k) {
  669. k = found + 10;
  670. uid = G_realloc(uid, k * sizeof(int));
  671. }
  672. i = found;
  673. uid[i] = n->uid;
  674. found++;
  675. }
  676. }
  677. /* look on the other side ? */
  678. dir = s[top].dir;
  679. if (n->c[(int)n->dim] >= sn.c[(int)n->dim] &&
  680. n->c[(int)n->dim] <= sn.c[(int)n->dim + t->ndims]) {
  681. /* go down the other side */
  682. top++;
  683. s[top].n = n->child[!dir];
  684. while (s[top].n) {
  685. n = s[top].n;
  686. dir = cmp(&sn, n, n->dim) > 0;
  687. s[top].dir = dir;
  688. s[top].v = 0;
  689. top++;
  690. s[top].n = n->child[dir];
  691. }
  692. }
  693. }
  694. }
  695. *puid = uid;
  696. return found;
  697. }
  698. /* initialize tree traversal
  699. * (re-)sets trav structure
  700. * returns 0
  701. */
  702. int kdtree_init_trav(struct kdtrav *trav, struct kdtree *tree)
  703. {
  704. trav->tree = tree;
  705. trav->curr_node = tree->root;
  706. trav->first = 1;
  707. trav->top = 0;
  708. return 0;
  709. }
  710. /* traverse the tree
  711. * useful to get all items in the tree non-recursively
  712. * struct kdtrav *trav needs to be initialized first
  713. * returns 1, 0 when finished
  714. */
  715. int kdtree_traverse(struct kdtrav *trav, double *c, int *uid)
  716. {
  717. if (trav->curr_node == NULL) {
  718. if (trav->first)
  719. G_debug(1, "k-d tree: empty tree");
  720. else
  721. G_debug(1, "k-d tree: finished traversing");
  722. return 0;
  723. }
  724. if (trav->first) {
  725. trav->first = 0;
  726. return kdtree_first(trav, c, uid);
  727. }
  728. return kdtree_next(trav, c, uid);
  729. }
  730. /**********************************************/
  731. /* internal functions */
  732. /**********************************************/
  733. static int kdtree_replace(struct kdtree *t, struct kdnode *r)
  734. {
  735. double mindist;
  736. int rdir, ordir, dir;
  737. int ld, rd;
  738. struct kdnode *n, *rn, *or;
  739. struct kdstack {
  740. struct kdnode *n;
  741. int dir;
  742. char v;
  743. } s[256];
  744. int top, top2;
  745. int is_leaf;
  746. int nr;
  747. if (!r)
  748. return 0;
  749. if (!r->child[0] && !r->child[1])
  750. return 0;
  751. /* do not call kdtree_balance in this fn, this can cause
  752. * stack overflow due to too many recursive calls */
  753. /* find replacement for r
  754. * overwrite r, delete replacement */
  755. nr = 0;
  756. /* pick a subtree */
  757. rdir = 1;
  758. or = r;
  759. ld = (!or->child[0] ? -1 : or->child[0]->depth);
  760. rd = (!or->child[1] ? -1 : or->child[1]->depth);
  761. if (ld > rd) {
  762. rdir = 0;
  763. }
  764. /* replace old root, make replacement the new root
  765. * repeat until replacement is leaf */
  766. ordir = rdir;
  767. is_leaf = 0;
  768. s[0].n = or;
  769. s[0].dir = ordir;
  770. top2 = 1;
  771. mindist = -1;
  772. while (!is_leaf) {
  773. rn = NULL;
  774. /* find replacement for old root */
  775. top = top2;
  776. s[top].n = or->child[ordir];
  777. n = s[top].n;
  778. rn = n;
  779. mindist = or->c[(int)or->dim] - n->c[(int)or->dim];
  780. if (ordir)
  781. mindist = -mindist;
  782. /* go down */
  783. while (s[top].n) {
  784. n = s[top].n;
  785. dir = !ordir;
  786. if (n->dim != or->dim)
  787. dir = cmp(or, n, n->dim) > 0;
  788. s[top].dir = dir;
  789. s[top].v = 0;
  790. top++;
  791. s[top].n = n->child[dir];
  792. }
  793. /* go back up */
  794. while (top > top2) {
  795. top--;
  796. if (!s[top].v) {
  797. s[top].v = 1;
  798. n = s[top].n;
  799. if ((cmp(rn, n, or->dim) > 0) == ordir) {
  800. rn = n;
  801. mindist = or->c[(int)or->dim] - n->c[(int)or->dim];
  802. if (ordir)
  803. mindist = -mindist;
  804. }
  805. /* look on the other side ? */
  806. dir = s[top].dir;
  807. if (n->dim != or->dim &&
  808. mindist >= fabs(n->c[(int)n->dim] - n->c[(int)n->dim])) {
  809. /* go down the other side */
  810. top++;
  811. s[top].n = n->child[!dir];
  812. while (s[top].n) {
  813. n = s[top].n;
  814. dir = !ordir;
  815. if (n->dim != or->dim)
  816. dir = cmp(or, n, n->dim) > 0;
  817. s[top].dir = dir;
  818. s[top].v = 0;
  819. top++;
  820. s[top].n = n->child[dir];
  821. }
  822. }
  823. }
  824. }
  825. #ifdef KD_DEBUG
  826. if (!rn)
  827. G_fatal_error("No replacement");
  828. if (ordir && or->c[(int)or->dim] > rn->c[(int)or->dim])
  829. G_fatal_error("rn is smaller");
  830. if (!ordir && or->c[(int)or->dim] < rn->c[(int)or->dim])
  831. G_fatal_error("rn is larger");
  832. if (or->child[1]) {
  833. dir = cmp(or->child[1], rn, or->dim);
  834. if (dir < 0) {
  835. int i;
  836. for (i = 0; i < t->ndims; i++)
  837. G_message("rn c %g, or child c %g",
  838. rn->c[i], or->child[1]->c[i]);
  839. G_fatal_error("Right child of old root is smaller than rn, dir is %d", ordir);
  840. }
  841. }
  842. if (or->child[0]) {
  843. dir = cmp(or->child[0], rn, or->dim);
  844. if (dir > 0) {
  845. int i;
  846. for (i = 0; i < t->ndims; i++)
  847. G_message("rn c %g, or child c %g",
  848. rn->c[i], or->child[0]->c[i]);
  849. G_fatal_error("Left child of old root is larger than rn, dir is %d", ordir);
  850. }
  851. }
  852. #endif
  853. is_leaf = (rn->child[0] == NULL && rn->child[1] == NULL);
  854. #ifdef KD_DEBUG
  855. if (is_leaf && rn->depth != 0)
  856. G_fatal_error("rn is leaf but depth is %d", (int)rn->depth);
  857. if (!is_leaf && rn->depth <= 0)
  858. G_fatal_error("rn is not leaf but depth is %d", (int)rn->depth);
  859. #endif
  860. nr++;
  861. /* go to replacement from or->child[ordir] */
  862. top = top2;
  863. dir = 1;
  864. while (dir) {
  865. n = s[top].n;
  866. dir = cmp(rn, n, n->dim);
  867. if (dir) {
  868. s[top].dir = dir > 0;
  869. top++;
  870. s[top].n = n->child[dir > 0];
  871. if (!s[top].n) {
  872. G_fatal_error("(Last) replacement disappeared %d", nr);
  873. }
  874. }
  875. }
  876. #ifdef KD_DEBUG
  877. if (s[top].n != rn)
  878. G_fatal_error("rn is unreachable from or");
  879. #endif
  880. top2 = top;
  881. s[top2 + 1].n = NULL;
  882. /* copy replacement to old root */
  883. memcpy(or->c, rn->c, t->csize);
  884. or->uid = rn->uid;
  885. if (!is_leaf) {
  886. /* make replacement the old root */
  887. or = rn;
  888. /* pick a subtree */
  889. ordir = 1;
  890. ld = (!or->child[0] ? -1 : or->child[0]->depth);
  891. rd = (!or->child[1] ? -1 : or->child[1]->depth);
  892. if (ld > rd) {
  893. ordir = 0;
  894. }
  895. s[top2].dir = ordir;
  896. top2++;
  897. }
  898. }
  899. if (!rn)
  900. G_fatal_error("No replacement at all");
  901. /* delete last replacement */
  902. if (s[top2].n != rn) {
  903. G_fatal_error("Wrong top2 for last replacement");
  904. }
  905. top = top2 - 1;
  906. n = s[top].n;
  907. dir = s[top].dir;
  908. if (n->child[dir] != rn) {
  909. G_fatal_error("Last replacement disappeared");
  910. }
  911. kdtree_free_node(rn);
  912. n->child[dir] = NULL;
  913. t->count--;
  914. kdtree_update_node(t, n);
  915. top++;
  916. /* go back up */
  917. while (top) {
  918. top--;
  919. n = s[top].n;
  920. #ifdef KD_DEBUG
  921. /* debug directions */
  922. if (n->child[0]) {
  923. if (cmp(n->child[0], n, n->dim) > 0)
  924. G_warning("Left child is larger");
  925. }
  926. if (n->child[1]) {
  927. if (cmp(n->child[1], n, n->dim) < 1)
  928. G_warning("Right child is not larger");
  929. }
  930. #endif
  931. /* update node */
  932. kdtree_update_node(t, n);
  933. }
  934. return nr;
  935. }
  936. static int kdtree_balance(struct kdtree *t, struct kdnode *r, int bmode)
  937. {
  938. struct kdnode *or;
  939. int dir;
  940. int rd, ld;
  941. int old_depth;
  942. int btol;
  943. if (!r) {
  944. return 0;
  945. }
  946. ld = (!r->child[0] ? -1 : r->child[0]->depth);
  947. rd = (!r->child[1] ? -1 : r->child[1]->depth);
  948. old_depth = MAX(ld, rd) + 1;
  949. if (old_depth != r->depth) {
  950. G_warning("balancing: depth is wrong: %d != %d", r->depth, old_depth);
  951. kdtree_update_node(t, r);
  952. }
  953. /* subtree difference */
  954. btol = t->btol;
  955. if (!r->child[0] || !r->child[1])
  956. btol = 2;
  957. dir = -1;
  958. ld = (!r->child[0] ? -1 : r->child[0]->depth);
  959. rd = (!r->child[1] ? -1 : r->child[1]->depth);
  960. if (ld > rd + btol) {
  961. dir = 0;
  962. }
  963. else if (rd > ld + btol) {
  964. dir = 1;
  965. }
  966. else {
  967. return 0;
  968. }
  969. or = kdtree_newnode(t);
  970. memcpy(or->c, r->c, t->csize);
  971. or->uid = r->uid;
  972. or->dim = t->nextdim[r->dim];
  973. if (!kdtree_replace(t, r))
  974. G_fatal_error("kdtree_balance: nothing replaced");
  975. #ifdef KD_DEBUG
  976. if (!cmp(r, or, r->dim)) {
  977. G_warning("kdtree_balance: replacement failed");
  978. kdtree_free_node(or);
  979. return 0;
  980. }
  981. #endif
  982. r->child[!dir] = kdtree_insert2(t, r->child[!dir], or, bmode, 1); /* bmode */
  983. /* update node */
  984. kdtree_update_node(t, r);
  985. if (r->depth == old_depth) {
  986. G_debug(4, "balancing had no effect");
  987. return 1;
  988. }
  989. if (r->depth > old_depth)
  990. G_fatal_error("balancing failed");
  991. return 1;
  992. }
  993. static struct kdnode *kdtree_insert2(struct kdtree *t, struct kdnode *r,
  994. struct kdnode *nnew,
  995. int balance, int dc)
  996. {
  997. struct kdnode *n;
  998. struct kdstack {
  999. struct kdnode *n;
  1000. int dir;
  1001. } s[256];
  1002. int top;
  1003. int dir;
  1004. int bmode;
  1005. if (!r) {
  1006. r = nnew;
  1007. t->count++;
  1008. return r;
  1009. }
  1010. /* level of recursion */
  1011. rcalls++;
  1012. if (rcallsmax < rcalls)
  1013. rcallsmax = rcalls;
  1014. /* balancing modes
  1015. * bmode = 0: no recursion (only insert -> balance -> insert)
  1016. * slower, higher tree depth
  1017. * bmode = 1: recursion (insert -> balance -> insert -> balance ...)
  1018. * faster, more compact tree
  1019. * */
  1020. bmode = 1;
  1021. /* find node with free child */
  1022. top = 0;
  1023. s[top].n = r;
  1024. while (s[top].n) {
  1025. n = s[top].n;
  1026. if (!cmpc(nnew, n, t) && (!dc || nnew->uid == n->uid)) {
  1027. G_debug(1, "KD node exists already, nothing to do");
  1028. kdtree_free_node(nnew);
  1029. if (!balance) {
  1030. rcalls--;
  1031. return r;
  1032. }
  1033. break;
  1034. }
  1035. dir = cmp(nnew, n, n->dim) > 0;
  1036. s[top].dir = dir;
  1037. top++;
  1038. if (top > 255)
  1039. G_fatal_error("depth too large: %d", top);
  1040. s[top].n = n->child[dir];
  1041. }
  1042. if (!s[top].n) {
  1043. /* insert to child pointer of parent */
  1044. top--;
  1045. n = s[top].n;
  1046. dir = s[top].dir;
  1047. n->child[dir] = nnew;
  1048. nnew->dim = t->nextdim[n->dim];
  1049. t->count++;
  1050. top++;
  1051. }
  1052. /* go back up */
  1053. while (top) {
  1054. top--;
  1055. n = s[top].n;
  1056. /* update node */
  1057. kdtree_update_node(t, n);
  1058. /* do not balance on the way back up */
  1059. #ifdef KD_DEBUG
  1060. /* debug directions */
  1061. if (n->child[0]) {
  1062. if (cmp(n->child[0], n, n->dim) > 0)
  1063. G_warning("Insert2: Left child is larger");
  1064. }
  1065. if (n->child[1]) {
  1066. if (cmp(n->child[1], n, n->dim) < 1)
  1067. G_warning("Insert2: Right child is not larger");
  1068. }
  1069. #endif
  1070. }
  1071. if (balance) {
  1072. int iter, bmode2;
  1073. /* fix any inconsistencies in the (sub-)tree */
  1074. iter = 0;
  1075. bmode2 = 0;
  1076. top = 0;
  1077. s[top].n = r;
  1078. while (top >= 0) {
  1079. n = s[top].n;
  1080. /* top-down balancing
  1081. * slower but more compact */
  1082. if (!bmode2) {
  1083. while (kdtree_balance(t, n, bmode));
  1084. }
  1085. /* go down */
  1086. if (n->child[0] && n->child[0]->balance) {
  1087. dir = 0;
  1088. top++;
  1089. s[top].n = n->child[dir];
  1090. }
  1091. else if (n->child[1] && n->child[1]->balance) {
  1092. dir = 1;
  1093. top++;
  1094. s[top].n = n->child[dir];
  1095. }
  1096. /* go back up */
  1097. else {
  1098. /* bottom-up balancing
  1099. * faster but less compact */
  1100. if (bmode2) {
  1101. while (kdtree_balance(t, n, bmode));
  1102. }
  1103. top--;
  1104. if (top >= 0) {
  1105. kdtree_update_node(t, s[top].n);
  1106. }
  1107. if (!bmode2 && top == 0) {
  1108. iter++;
  1109. if (iter == 2) {
  1110. /* the top node has been visited twice,
  1111. * switch from top-down to bottom-up balancing */
  1112. iter = 0;
  1113. bmode2 = 1;
  1114. }
  1115. }
  1116. }
  1117. }
  1118. }
  1119. rcalls--;
  1120. return r;
  1121. }
  1122. /* start traversing the tree
  1123. * returns pointer to first item
  1124. */
  1125. static int kdtree_first(struct kdtrav *trav, double *c, int *uid)
  1126. {
  1127. /* get smallest item */
  1128. while (trav->curr_node->child[0] != NULL) {
  1129. trav->up[trav->top++] = trav->curr_node;
  1130. trav->curr_node = trav->curr_node->child[0];
  1131. }
  1132. memcpy(c, trav->curr_node->c, trav->tree->csize);
  1133. *uid = trav->curr_node->uid;
  1134. return 1;
  1135. }
  1136. /* continue traversing the tree in ascending order
  1137. * returns pointer to data item, NULL when finished
  1138. */
  1139. static int kdtree_next(struct kdtrav *trav, double *c, int *uid)
  1140. {
  1141. if (trav->curr_node->child[1] != NULL) {
  1142. /* something on the right side: larger item */
  1143. trav->up[trav->top++] = trav->curr_node;
  1144. trav->curr_node = trav->curr_node->child[1];
  1145. /* go down, find smallest item in this branch */
  1146. while (trav->curr_node->child[0] != NULL) {
  1147. trav->up[trav->top++] = trav->curr_node;
  1148. trav->curr_node = trav->curr_node->child[0];
  1149. }
  1150. }
  1151. else {
  1152. /* at smallest item in this branch, go back up */
  1153. struct kdnode *last;
  1154. do {
  1155. if (trav->top == 0) {
  1156. trav->curr_node = NULL;
  1157. break;
  1158. }
  1159. last = trav->curr_node;
  1160. trav->curr_node = trav->up[--trav->top];
  1161. } while (last == trav->curr_node->child[1]);
  1162. }
  1163. if (trav->curr_node != NULL) {
  1164. memcpy(c, trav->curr_node->c, trav->tree->csize);
  1165. *uid = trav->curr_node->uid;
  1166. return 1;
  1167. }
  1168. return 0; /* finished traversing */
  1169. }