kdtree.c 28 KB

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