kdtree_common.c 8.88 KB
Newer Older
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1
2
3
4
5
6
7
8
9
10
/*!\file kdtree_common.c
 * \brief Routines common to the Cartesian and spherical kd-tree versions
 *
 */

#include "kdtree.h"
#include "pqueue.h"


extern int pmergesort(void *base, size_t nmemb, size_t size,
11
12
                      int (*compar) (const void *, const void *),
                      int max_threads);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
13
14
15
16
17
18
19
20


/* ********************************************************************

   general utility functions 

   ********************************************************************* */

21
void *
Uwe Schulzweida's avatar
Uwe Schulzweida committed
22
23
24
25
26
27
28
29
kd_malloc(size_t size, const char *msg)
{
    void *ptr;
    if ((ptr = malloc(size)) == NULL)
        perror(msg);
    return ptr;
}

30
31
kdata_t
kd_sqr(kdata_t x)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
32
{
33
    return x == 0 ? 0 : x * x;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
34
35
}

36
int
Uwe Schulzweida's avatar
Uwe Schulzweida committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
kd_isleaf(struct kdNode *n)
{
    return (n->left || n->right) ? 0 : 1;
}

/* end utility functions */

/* *******************************************************************
   
   Helper functions for debugging

   ******************************************************************* */

void
kd_printNode(struct kdNode *node)
{
    if (!node) {
        fprintf(stderr, "Node is empty.\n");
        return;
    }
    printf("Node %p at (%f, %f)\n", (void *) node, node->location[0],
           node->location[1]);

    printf("Split axis: %d\n", node->split);
    printf("Corners: (%f, %f)\t(%f, %f)\n", node->min[0], node->min[1],
           node->max[0], node->max[1]);
    printf("Children: %p\t%p\n", (void *) node->left, (void *) node->right);
    printf("Index: %u\n", node->index);

    printf("\n");

}

void
kd_printTree(struct kdNode *node)
{
    if (node == NULL)
        return;

    kd_printTree(node->left);
    if (kd_isleaf(node) )
        printf("%f\t%f\n", node->location[0], node->location[1]);
    kd_printTree(node->right);
}

/* End helper functions */

/* ******************************************************************
   
   Functions for building and destroying trees 

   ******************************************************************** */

90
91
92
93
94
95
static int
_compPoints0(const void *p1, const void *p2)
{
    struct kd_point *a = (struct kd_point *) p1;
    struct kd_point *b = (struct kd_point *) p2;

96
97
98
99
    int ret = (a->point[0] > b->point[0]) ? 1 : (a->point[0] < b->point[0]) ? -1 : 0;
    if ( ret == 0 ) ret = (a->index > b->index) ? 1 : (a->index < b->index) ? -1 : 0;

    return ret;
100
101
102
103
104
105
106
107
}

static int
_compPoints1(const void *p1, const void *p2)
{
    struct kd_point *a = (struct kd_point *) p1;
    struct kd_point *b = (struct kd_point *) p2;

108
109
    int ret = (a->point[1] > b->point[1]) ? 1 : (a->point[1] < b->point[1]) ? -1 : 0;
    if ( ret == 0 ) ret = (a->index > b->index) ? 1 : (a->index < b->index) ? -1 : 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
110

111
    return ret;
112
113
114
115
116
117
118
119
}

static int
_compPoints2(const void *p1, const void *p2)
{
    struct kd_point *a = (struct kd_point *) p1;
    struct kd_point *b = (struct kd_point *) p2;

120
121
    int ret = (a->point[2] > b->point[2]) ? 1 : (a->point[2] < b->point[2]) ? -1 : 0;
    if ( ret == 0 ) ret = (a->index > b->index) ? 1 : (a->index < b->index) ? -1 : 0;
122

123
    return ret;
124
}
125

Uwe Schulzweida's avatar
Uwe Schulzweida committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/*
void kd_quick_sort(struct kd_point *a, int n, int idx)
{
    int i, j;
    struct kd_point p, t;
    if ( n < 2 ) return;
    p = a[n / 2];
    for ( i = 0, j = n - 1;; i++, j-- )
      {
        while ( a[i].point[idx] < p.point[idx] ) i++;
        while ( p.point[idx] < a[j].point[idx] ) j--;
        if ( i >= j ) break;
        t = a[i];
        a[i] = a[j];
        a[j] = t;
      }
    kd_quick_sort(a, i, idx);
    kd_quick_sort(a + i, n - i, idx);
}
*/

Uwe Schulzweida's avatar
Uwe Schulzweida committed
147
148
149
150
151
void *
kd_doBuildTree(void *threadarg)
{
    int sortaxis;
    unsigned long pivot;
152
    kdata_t tmpMinLeft[KD_MAX_DIM], tmpMaxLeft[KD_MAX_DIM], tmpMinRight[KD_MAX_DIM], tmpMaxRight[KD_MAX_DIM];
Uwe Schulzweida's avatar
Uwe Schulzweida committed
153
154
155
    struct kdNode *node;
    struct kd_point *points;
    unsigned long nPoints;
156
    kdata_t *min, *max;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    int depth, dim, max_threads;
    pthread_t threads[2];
    pthread_attr_t attr;
    struct kd_thread_data *argleft, *argright;
    struct kd_thread_data *my_data = (struct kd_thread_data *) threadarg;

    points = my_data->points;
    nPoints = my_data->nPoints;
    min = my_data->min;
    max = my_data->max;
    depth = my_data->depth;
    max_threads = my_data->max_threads;
    dim = my_data->dim;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    sortaxis = depth % dim;
175

Uwe Schulzweida's avatar
Uwe Schulzweida committed
176
177
178
179
180
181
182
183
184
185
186
    if (nPoints == 1) {
        if ((node = kd_allocNode(points, 0, min, max, sortaxis, dim)) == NULL)
            return NULL;
        node->index = points[0].index;
        return node;
    }

    /*
     * If this iteration is allowed to start more threads, we first
     * use them to parallelize the sorting 
     */
187
188
189
    int (*qcomp) (const void *, const void *);
    if      ( sortaxis == 0 ) qcomp = _compPoints0;
    else if ( sortaxis == 1 ) qcomp = _compPoints1;
190
    else                      qcomp = _compPoints2;
191
192

    pmergesort(points, nPoints, sizeof(struct kd_point), qcomp, max_threads);
193

Uwe Schulzweida's avatar
Uwe Schulzweida committed
194
195
196
197
    pivot = nPoints / 2;
    if ((node = kd_allocNode(points, pivot, min, max, sortaxis, dim)) == NULL)
        return NULL;

198
199
    memcpy(tmpMinLeft, min, dim * sizeof(kdata_t));
    memcpy(tmpMaxLeft, max, dim * sizeof(kdata_t));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
200
201
202
203
204
205
206
207
208
209
210
    tmpMaxLeft[sortaxis] = node->location[sortaxis];
    argleft =
        kd_buildArg(points, pivot, tmpMinLeft, tmpMaxLeft,
                    depth + 1, max_threads / 2, dim);
    if (!argleft) {
        kd_destroyTree(node);
        return NULL;
    }
    if (max_threads > 1) {
        pthread_create(&threads[0], &attr, kd_doBuildTree, (void *) argleft);
    } else {
Oliver Heidmann's avatar
Oliver Heidmann committed
211
        node->left = (kdNode *)kd_doBuildTree((void *) argleft);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
212
213
214
215
216
217
218
        free(argleft);
        if (!node->left) {
            kd_destroyTree(node);
            return NULL;
        }
    }

219
220
    memcpy(tmpMinRight, min, dim * sizeof(kdata_t));
    memcpy(tmpMaxRight, max, dim * sizeof(kdata_t));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
221
222
223
224
225
226
227
228
229
230
231
    tmpMinRight[sortaxis] = node->location[sortaxis];
    argright = kd_buildArg(&points[pivot], nPoints - pivot,
                           tmpMinRight, tmpMaxRight, depth + 1,
                           max_threads / 2, dim);
    if (!argright) {
        kd_destroyTree(node);
        return NULL;
    }
    if (max_threads > 1) {
        pthread_create(&threads[1], &attr, kd_doBuildTree, (void *) argright);
    } else {
Oliver Heidmann's avatar
Oliver Heidmann committed
232
        node->right = (kdNode *)kd_doBuildTree((void *) argright);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
233
234
235
236
237
238
239
        free(argright);
        if (!node->right) {
            kd_destroyTree(node);
            return NULL;
        }
    }
    if (max_threads > 1) {
Oliver Heidmann's avatar
Oliver Heidmann committed
240
        pthread_join(threads[0], (void **) (&node->left));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
241
        free(argleft);
Oliver Heidmann's avatar
Oliver Heidmann committed
242
        pthread_join(threads[1], (void **) (&node->right));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
        free(argright);
        if (!node->left || !node->right) {
            kd_destroyTree(node);
            return NULL;
        }
    }
    return (void *) node;
}


void
kd_freeNode(kdNode *node)
{
    if ( node ) free(node);
    return;
}


struct kd_thread_data *
kd_buildArg(struct kd_point *points,
            unsigned long nPoints,
264
            kdata_t *min, kdata_t *max,
Uwe Schulzweida's avatar
Uwe Schulzweida committed
265
266
267
268
            int depth, int max_threads, int dim)
{
    struct kd_thread_data *d;

Oliver Heidmann's avatar
Oliver Heidmann committed
269
    if ((d = (kd_thread_data *)kd_malloc(sizeof(kd_thread_data), "kd_thread_data")) == NULL)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
270
271
272
        return NULL;
    d->points = points;
    d->nPoints = nPoints;
273
274
    memcpy(d->min, min, dim*sizeof(kdata_t));
    memcpy(d->max, max, dim*sizeof(kdata_t));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
275
276
277
278
279
280
281
282
283
    d->depth = depth;
    d->max_threads = max_threads;
    d->dim = dim;
    return d;
}


struct kdNode *
kd_allocNode(struct kd_point *points, unsigned long pivot,
284
             kdata_t *min, kdata_t *max, int axis, int dim)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
285
286
287
{
    struct kdNode *node;

Oliver Heidmann's avatar
Oliver Heidmann committed
288
    if ((node = (kdNode *)kd_malloc(sizeof(kdNode), "kd_allocNode (node): ")) == NULL)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
289
290
        return NULL;
    node->split = axis;
291
292
293
    memcpy(node->location, points[pivot].point, dim * sizeof(kdata_t));
    memcpy(node->min, min, dim * sizeof(kdata_t));
    memcpy(node->max, max, dim * sizeof(kdata_t));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
    node->left = node->right = NULL;
    node->index = 0;
    return node;
}

/*!
 * \brief free the kd-tree data structure, 
 *
 * \param node the root node of the tree to be destroyed
 *
 * \param *destr a pointer to the destructor function for the data container.
 *
 * \return This function does not return a value
 */
void
kd_destroyTree(struct kdNode *node)
{
    if (node == NULL)
        return;

    kd_destroyTree(node->left);
    kd_destroyTree(node->right);
    kd_freeNode(node);
}

/* end of tree construction and destruction */

/* Functions dealing with result heaps */

/* Insert the sub-tree starting at node into the result heap res */
int
kd_insertResTree(struct kdNode *node, struct pqueue *res)
{
    struct resItem *point;

    if (node == NULL)
        return 1;

    if (!kd_insertResTree(node->left, res))
        return 0;
    if (kd_isleaf(node)) {
Oliver Heidmann's avatar
Oliver Heidmann committed
335
        if ((point = (struct resItem *)kd_malloc(sizeof(struct resItem), "kd_insertResTree: "))
Uwe Schulzweida's avatar
Uwe Schulzweida committed
336
337
338
339
340
341
342
343
344
345
346
            == NULL)
            return 0;

        point->node = node;
        point->dist_sq = -1;
        pqinsert(res, point);
    }
    if (!kd_insertResTree(node->right, res))
        return 0;
    return 1;
}