File: cluster.c

package info (click to toggle)
grass 8.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 277,040 kB
  • sloc: ansic: 460,798; python: 227,732; cpp: 42,026; sh: 11,262; makefile: 7,007; xml: 3,637; sql: 968; lex: 520; javascript: 484; yacc: 450; asm: 387; perl: 157; sed: 25; objc: 6; ruby: 4
file content (468 lines) | stat: -rw-r--r-- 16,158 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/****************************************************************************
 *
 * MODULE:       r.clump
 *
 * AUTHOR(S):    Michael Shapiro - CERL
 *               Markus Metz
 *
 * PURPOSE:      Recategorizes data in a raster map layer by grouping cells
 *               that form physically discrete areas into unique categories.
 *
 * COPYRIGHT:    (C) 2006-2016 by the GRASS Development Team
 *
 *               This program is free software under the GNU General Public
 *               License (>=v2). Read the file COPYING that comes with GRASS
 *               for details.
 *
 ***************************************************************************/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <grass/gis.h>
#include <grass/raster.h>
#include <grass/glocale.h>
#include "iseg.h"

#define INCR 1024

/* defeats the purpose of padding ... */
#define CISNULL(r, c)              \
    (((c) == 0 || (c) == ncols + 1 \
          ? 1                      \
          : (FLAG_GET(globals->null_flag, (r), (c - 1)))))

CELL cluster_bands(struct globals *globals)
{
    register int col;
    register int i, n;

    /* input */
    DCELL **prev_in, **cur_in, **temp_in;
    struct ngbr_stats Ri, Rk, Rn;
    int nin;
    int diag;
    int bcol;

    /* output */
    CELL OLD, NEW;
    CELL *temp_clump, out_cell;
    CELL *prev_clump, *cur_clump;
    CELL *index, *renumber;
    CELL label, cellmax;
    int nrows, ncols;
    int row;
    int len;
    int nalloc;
    char *cname;
    int cfd, csize;
    CELL cat;
    int mwrow, mwrow1, mwrow2, mwnrows, mwcol, mwcol1, mwcol2, mwncols, radiusc;
    double diff, diff2, avgdiff, ka2, hspat, hspat2;
    double hspec, hspecad, hspec2, hspec2ad;
    LARGEINT count;

    G_message(_("%d-band clustering with threshold %g"), globals->nbands,
              globals->hr);

    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    hspec = globals->hr;
    hspec2 = globals->hr * globals->hr;
    nin = globals->nbands;
    diag = (globals->nn == 8);
    radiusc = globals->hs;
    mwnrows = mwncols = radiusc * 2 + 1;

    /* spatial bandwidth */
    hspat = globals->hs;
    if (hspat < 1)
        hspat = 1.5;
    hspat2 = hspat * hspat;

    cellmax = ((CELL)1 << (sizeof(CELL) * 8 - 2)) - 1;
    cellmax += ((CELL)1 << (sizeof(CELL) * 8 - 2));

    Ri.mean = NULL;
    Rk.mean = NULL;
    Rn.mean = G_malloc(globals->datasize);

    /* allocate clump index */
    /* TODO: support smallest label ID > 1 */
    nalloc = INCR;
    index = (CELL *)G_malloc(nalloc * sizeof(CELL));
    index[0] = 0;
    renumber = NULL;

    /* allocate DCELL buffers two columns larger than current window */
    prev_in = (DCELL **)G_malloc(sizeof(DCELL *) * (ncols + 2));
    cur_in = (DCELL **)G_malloc(sizeof(DCELL *) * (ncols + 2));

    prev_in[0] = (DCELL *)G_malloc(globals->datasize * (ncols + 2) * nin);
    cur_in[0] = (DCELL *)G_malloc(globals->datasize * (ncols + 2) * nin);

    Rast_set_d_null_value(cur_in[0], (ncols + 2) * nin);
    Rast_set_d_null_value(prev_in[0], (ncols + 2) * nin);

    for (i = 1; i < ncols + 2; i++) {
        prev_in[i] = prev_in[i - 1] + nin;
        cur_in[i] = cur_in[i - 1] + nin;
    }

    /* allocate CELL buffers two columns larger than current window */
    len = (ncols + 2) * sizeof(CELL);
    prev_clump = (CELL *)G_malloc(len);
    cur_clump = (CELL *)G_malloc(len);

    /* temp file for initial clump IDs */
    cname = G_tempfile();
    if ((cfd = open(cname, O_RDWR | O_CREAT | O_EXCL, 0600)) < 0)
        G_fatal_error(_("Unable to open temp file"));
    csize = ncols * sizeof(CELL);

    /* initialize clump labels */
    G_zero(cur_clump, len);
    G_zero(prev_clump, len);
    /* TODO: support smallest label ID > 1 */
    label = 0;

    /****************************************************
     *                      PASS 1                      *
     * pass thru the input, create initial clump labels *
     ****************************************************/

    G_message(_("Assigning initial region IDs..."));
    for (row = 0; row < nrows; row++) {
        G_percent(row, nrows, 2);

        for (col = 1; col <= ncols; col++) {

            /* get band values */
            Segment_get(globals->bands_out, (void *)cur_in[col], row, col - 1);
            Ri.mean = cur_in[col];

            if (CISNULL(row, col)) {
                cur_clump[col] = 0;
                continue;
            }

            hspec2ad = hspec2;

            if (globals->ms_adaptive) {
                /* adapt initial range bandwidth */

                mwrow1 = row - radiusc;
                mwrow2 = mwrow1 + mwnrows;
                if (mwrow1 < 0)
                    mwrow1 = 0;
                if (mwrow2 > nrows)
                    mwrow2 = nrows;

                mwcol1 = col - radiusc;
                mwcol2 = mwcol1 + mwncols;
                if (mwcol1 < 0)
                    mwcol1 = 0;
                if (mwcol2 > ncols)
                    mwcol2 = ncols;

                ka2 = hspec2; /* OTB: conductance parameter */

                avgdiff = 0;
                count = 0;
                for (mwrow = mwrow1; mwrow < mwrow2; mwrow++) {
                    for (mwcol = mwcol1; mwcol < mwcol2; mwcol++) {
                        if ((FLAG_GET(globals->null_flag, mwrow, mwcol)))
                            continue;
                        if (mwrow == row && mwcol == col)
                            continue;

                        diff = mwrow - row;
                        diff2 = diff * diff;
                        diff = mwcol - col;
                        diff2 += diff * diff;

                        if (diff2 <= hspat2) {

                            Segment_get(globals->bands_out, (void *)Rn.mean,
                                        mwrow, mwcol);

                            /* get spectral distance */
                            diff2 = (globals->calculate_similarity)(&Ri, &Rn,
                                                                    globals);

                            avgdiff += sqrt(diff2);
                            count++;
                        }
                    }
                }
                hspec2ad = 0;
                if (avgdiff > 0) {
                    avgdiff /= count;
                    hspecad = hspec;
                    /* OTB-like, contrast enhancing */
                    hspecad = exp(-avgdiff * avgdiff / (2 * ka2)) * avgdiff;
                    /* preference for large regions, from Perona Malik 1990
                     * if the settings are right, it could be used to reduce
                     * noise */
                    /* hspecad = 1 / (1 + (avgdiff * avgdiff / (2 * hspec2)));
                     */
                    hspec2ad = hspecad * hspecad;
                    G_debug(1, "avg spectral diff: %g", avgdiff);
                    G_debug(1, "initial hspec2: %g", hspec2);
                    G_debug(1, "adapted hspec2: %g", hspec2ad);
                }
            }

            /*
             * if the cell values are different to the left and above
             * (diagonal: and above left and above right)
             * then we must start a new clump
             *
             * this new clump may eventually collide with another
             * clump and will have to be merged
             */

            /* try to connect the current cell to an existing clump */
            OLD = NEW = 0;

            Rk.mean = cur_in[col - 1];

            /* same clump as to the left */
            if (!CISNULL(row, col - 1) &&
                globals->calculate_similarity(&Ri, &Rk, globals) <= hspec2ad) {
                OLD = cur_clump[col] = cur_clump[col - 1];
            }

            if (diag) {
                /* check above right, center, left, in that order */
                temp_clump = prev_clump + col + 1;
                bcol = col + 1;
                do {
                    Rk.mean = prev_in[bcol];
                    if (row > 0 && !CISNULL(row - 1, bcol) &&
                        globals->calculate_similarity(&Ri, &Rk, globals) <=
                            hspec2ad) {
                        cur_clump[col] = *temp_clump;
                        if (OLD == 0) {
                            OLD = *temp_clump;
                        }
                        else {
                            NEW = *temp_clump;

                            /* threshold > 0 and diagonal requires a bit of
                             * extra work because of bridge cells: A similar to
                             * B, B similar to C, but A not similar to C
                             * -> B is bridge cell */
                            if (NEW != OLD) {
                                CELL *temp_clump2;

                                /* conflict! preserve NEW clump ID and change
                                 * OLD clump ID. Must go back to the left in the
                                 * current row and to the right in the previous
                                 * row to change all the clump values as well.
                                 */

                                /* left of the current row from 1 to col - 1 */
                                temp_clump2 = cur_clump;
                                n = col - 1;
                                while (n-- > 0) {
                                    temp_clump2++; /* skip left edge */
                                    if (*temp_clump2 == OLD)
                                        *temp_clump2 = NEW;
                                }

                                /* right of previous row from col - 1 to ncols
                                 */
                                temp_clump2 = prev_clump + col - 1;
                                n = ncols - col + 2;
                                while (n-- > 0) {
                                    if (*temp_clump2 == OLD)
                                        *temp_clump2 = NEW;
                                    temp_clump2++;
                                }

                                /* modify the OLD index */
                                index[OLD] = NEW;

                                OLD = NEW;
                                NEW = 0;
                            }
                        }
                    }
                    temp_clump--;
                } while (bcol-- > col - 1);
            }
            else {
                /* check above */
                Rk.mean = prev_in[col];

                if (row > 0 && !CISNULL(row - 1, col) &&
                    globals->calculate_similarity(&Ri, &Rk, globals) <=
                        hspec2ad) {
                    temp_clump = prev_clump + col;
                    cur_clump[col] = *temp_clump;
                    if (OLD == 0) {
                        OLD = *temp_clump;
                    }
                    else {
                        NEW = *temp_clump;
                        if (NEW != OLD) {

                            /* conflict! preserve NEW clump ID and change OLD
                             * clump ID. Must go back to the left in the current
                             * row and to the right in the previous row to
                             * change all the clump values as well.
                             */

                            /* left of the current row from 1 to col - 1 */
                            temp_clump = cur_clump;
                            n = col - 1;
                            while (n-- > 0) {
                                temp_clump++; /* skip left edge */
                                if (*temp_clump == OLD)
                                    *temp_clump = NEW;
                            }

                            /* right of previous row from col + 1 to ncols */
                            temp_clump = prev_clump + col;
                            n = ncols - col;
                            while (n-- > 0) {
                                temp_clump++; /* skip col */
                                if (*temp_clump == OLD)
                                    *temp_clump = NEW;
                            }

                            /* modify the OLD index */
                            index[OLD] = NEW;

                            OLD = NEW;
                            NEW = 0;
                        }
                    }
                }
            }

            if (NEW == 0 || OLD == NEW) { /* ok */
                if (OLD == 0) {
                    /* start a new clump */
                    if (label == cellmax)
                        G_fatal_error(_("Too many objects: integer overflow"));

                    label++;
                    cur_clump[col] = label;
                    if (label >= nalloc) {
                        nalloc += INCR;
                        index = (CELL *)G_realloc(index, nalloc * sizeof(CELL));
                    }
                    index[label] = label;
                }
            }
            /* else the relabelling above failed */
        }

        /* write initial clump IDs */
        /* this works also with writing out cur_clump, but only
         * prev_clump is complete and will not change any more */
        if (row > 0) {
            if (write(cfd, prev_clump + 1, csize) != csize)
                G_fatal_error(_("Unable to write to temp file"));
        }

        /* switch the buffers so that the current buffer becomes the previous */
        temp_in = cur_in;
        cur_in = prev_in;
        prev_in = temp_in;

        temp_clump = cur_clump;
        cur_clump = prev_clump;
        prev_clump = temp_clump;
    }
    /* write last row with initial clump IDs */
    if (write(cfd, prev_clump + 1, csize) != csize)
        G_fatal_error(_("Unable to write to temp file"));
    G_percent(1, 1, 1);

    G_free(prev_in[0]);
    G_free(cur_in[0]);
    G_free(prev_in);
    G_free(cur_in);

    /* generate a renumbering scheme */
    G_message(_("Generating renumbering scheme..."));
    G_debug(1, "%d initial labels", label);
    /* allocate final clump ID */
    renumber = (CELL *)G_malloc((label + 1) * sizeof(CELL));
    renumber[0] = 0;
    cat = 0;
    G_percent(0, label, 1);
    for (n = 1; n <= label; n++) {
        G_percent(n, label, 1);
        OLD = n;
        NEW = index[n];
        if (OLD != NEW) {
            renumber[n] = 0;
            /* find valid clump ID */
            while (OLD != NEW) {
                OLD = NEW;
                NEW = index[OLD];
            }
            index[n] = NEW;
        }
        else
            /* set final clump id */
            renumber[n] = ++cat;
    }

    if (cat > cellmax - globals->max_rid)
        G_fatal_error(_("Too many objects: integer overflow"));

    /* rewind temp file */
    lseek(cfd, 0, SEEK_SET);

    /****************************************************
     *                      PASS 2                      *
     * apply renumbering scheme to initial clump labels *
     ****************************************************/

    /* the input raster is no longer needed,
     * using instead the temp file with initial clump labels */

    G_message(_("Assigning final region IDs..."));
    for (row = 0; row < nrows; row++) {

        G_percent(row, nrows, 2);

        if (read(cfd, cur_clump, csize) != csize)
            G_fatal_error(_("Unable to read from temp file"));

        temp_clump = cur_clump;

        for (col = 0; col < ncols; col++) {
            if (!(FLAG_GET(globals->null_flag, row, col))) {
                out_cell = renumber[index[*temp_clump]] + globals->max_rid;

                Segment_put(&globals->rid_seg, (void *)&out_cell, row, col);
            }
            temp_clump++;
        }
    }
    G_percent(1, 1, 1);

    close(cfd);
    unlink(cname);

    /* free */
    G_free(prev_clump);
    G_free(cur_clump);
    G_free(index);
    G_free(renumber);

    G_message(_("Found %d clumps"), cat);
    globals->max_rid += cat;

    return globals->max_rid;
}