main.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /****************************************************************************
  2. *
  3. * MODULE: r.neighbors
  4. * AUTHOR(S): Michael Shapiro, CERL (original contributor)
  5. * Markus Neteler <neteler itc.it>, Bob Covill <bcovill tekmap.ns.ca>,
  6. * Brad Douglas <rez touchofmadness.com>, Glynn Clements <glynn gclements.plus.com>,
  7. * Jachym Cepicky <jachym les-ejk.cz>, Jan-Oliver Wagner <jan intevation.de>,
  8. * Radim Blazek <radim.blazek gmail.com>
  9. *
  10. * PURPOSE: Makes each cell category value a function of the category values
  11. * assigned to the cells around it, and stores new cell values in an
  12. * output raster map layer
  13. * COPYRIGHT: (C) 1999-2006 by the GRASS Development Team
  14. *
  15. * This program is free software under the GNU General Public
  16. * License (>=v2). Read the file COPYING that comes with GRASS
  17. * for details.
  18. *
  19. *****************************************************************************/
  20. #include <string.h>
  21. #include <stdlib.h>
  22. #include <unistd.h>
  23. #include <grass/gis.h>
  24. #include <grass/raster.h>
  25. #include <grass/glocale.h>
  26. #include <grass/stats.h>
  27. #include "ncb.h"
  28. #include "local_proto.h"
  29. typedef int (*ifunc) (void);
  30. struct menu
  31. {
  32. stat_func *method; /* routine to compute new value */
  33. stat_func_w *method_w; /* routine to compute new value (weighted) */
  34. ifunc cat_names; /* routine to make category names */
  35. int copycolr; /* flag if color table can be copied */
  36. int half; /* whether to add 0.5 to result (redundant) */
  37. int otype; /* output type */
  38. char *name; /* method name */
  39. char *text; /* menu display - full description */
  40. };
  41. enum out_type {
  42. T_FLOAT = 1,
  43. T_INT = 2,
  44. T_COUNT = 3,
  45. T_COPY = 4,
  46. T_SUM = 5
  47. };
  48. #define NO_CATS 0
  49. /* modify this table to add new methods */
  50. static struct menu menu[] = {
  51. {c_ave, w_ave, NO_CATS, 1, 1, T_FLOAT, "average", "average value"},
  52. {c_median, w_median, NO_CATS, 1, 0, T_FLOAT, "median", "median value"},
  53. {c_mode, w_mode, NO_CATS, 1, 0, T_COPY, "mode", "most frequently occurring value"},
  54. {c_min, NULL, NO_CATS, 1, 0, T_COPY, "minimum", "lowest value"},
  55. {c_max, NULL, NO_CATS, 1, 0, T_COPY, "maximum", "highest value"},
  56. {c_range, NULL, NO_CATS, 1, 0, T_COPY, "range", "range value"},
  57. {c_stddev, w_stddev, NO_CATS, 0, 1, T_FLOAT, "stddev", "standard deviation"},
  58. {c_sum, w_sum, NO_CATS, 1, 0, T_SUM, "sum", "sum of values"},
  59. {c_count, w_count, NO_CATS, 0, 0, T_COUNT, "count", "count of non-NULL values"},
  60. {c_var, w_var, NO_CATS, 0, 1, T_FLOAT, "variance", "statistical variance"},
  61. {c_divr, NULL, divr_cats, 0, 0, T_INT, "diversity",
  62. "number of different values"},
  63. {c_intr, NULL, intr_cats, 0, 0, T_INT, "interspersion",
  64. "number of values different than center value"},
  65. {c_quart1, w_quart1, NO_CATS, 1, 0, T_FLOAT, "quart1", "first quartile"},
  66. {c_quart3, w_quart3, NO_CATS, 1, 0, T_FLOAT, "quart3", "third quartile"},
  67. {c_perc90, w_perc90, NO_CATS, 1, 0, T_FLOAT, "perc90", "ninetieth percentile"},
  68. {c_quant, w_quant, NO_CATS, 1, 0, T_FLOAT, "quantile", "arbitrary quantile"},
  69. {0, 0, 0, 0, 0, 0, 0, 0}
  70. };
  71. struct ncb ncb;
  72. struct output
  73. {
  74. const char *name;
  75. char title[1024];
  76. int fd;
  77. DCELL *buf;
  78. stat_func *method_fn;
  79. stat_func_w *method_fn_w;
  80. int copycolr;
  81. ifunc cat_names;
  82. int map_type;
  83. double quantile;
  84. };
  85. static int find_method(const char *method_name)
  86. {
  87. int i;
  88. for (i = 0; menu[i].name; i++)
  89. if (strcmp(menu[i].name, method_name) == 0)
  90. return i;
  91. G_fatal_error(_("Unknown method <%s>"), method_name);
  92. return -1;
  93. }
  94. static RASTER_MAP_TYPE output_type(RASTER_MAP_TYPE input_type, int weighted, int mode)
  95. {
  96. switch (mode) {
  97. case T_FLOAT:
  98. return DCELL_TYPE;
  99. case T_INT:
  100. return CELL_TYPE;
  101. case T_COUNT:
  102. return weighted ? DCELL_TYPE : CELL_TYPE;
  103. case T_COPY:
  104. return input_type;
  105. case T_SUM:
  106. return weighted ? DCELL_TYPE : input_type;
  107. default:
  108. G_fatal_error(_("Invalid out_type enumeration: %d"), mode);
  109. return -1;
  110. }
  111. }
  112. int main(int argc, char *argv[])
  113. {
  114. char *p;
  115. int in_fd;
  116. int selection_fd;
  117. int num_outputs;
  118. struct output *outputs = NULL;
  119. int copycolr, weights, have_weights_mask;
  120. char *selection;
  121. RASTER_MAP_TYPE map_type;
  122. int row, col;
  123. int readrow;
  124. int nrows, ncols;
  125. int i, n;
  126. struct Colors colr;
  127. struct Cell_head cellhd;
  128. struct Cell_head window;
  129. struct History history;
  130. struct GModule *module;
  131. struct
  132. {
  133. struct Option *input, *output, *selection;
  134. struct Option *method, *size;
  135. struct Option *title;
  136. struct Option *weight;
  137. struct Option *gauss;
  138. struct Option *quantile;
  139. } parm;
  140. struct
  141. {
  142. struct Flag *align, *circle;
  143. } flag;
  144. DCELL *values; /* list of neighborhood values */
  145. DCELL *values_tmp; /* list of neighborhood values */
  146. DCELL(*values_w)[2]; /* list of neighborhood values and weights */
  147. DCELL(*values_w_tmp)[2]; /* list of neighborhood values and weights */
  148. G_gisinit(argv[0]);
  149. module = G_define_module();
  150. G_add_keyword(_("raster"));
  151. G_add_keyword(_("algebra"));
  152. G_add_keyword(_("statistics"));
  153. G_add_keyword(_("aggregation"));
  154. G_add_keyword(_("neighbor"));
  155. G_add_keyword(_("focal statistics"));
  156. G_add_keyword(_("filter"));
  157. module->description =
  158. _("Makes each cell category value a "
  159. "function of the category values assigned to the cells "
  160. "around it, and stores new cell values in an output raster "
  161. "map layer.");
  162. parm.input = G_define_standard_option(G_OPT_R_INPUT);
  163. parm.selection = G_define_standard_option(G_OPT_R_INPUT);
  164. parm.selection->key = "selection";
  165. parm.selection->required = NO;
  166. parm.selection->description = _("Name of an input raster map to select the cells which should be processed");
  167. parm.output = G_define_standard_option(G_OPT_R_OUTPUT);
  168. parm.output->multiple = YES;
  169. parm.method = G_define_option();
  170. parm.method->key = "method";
  171. parm.method->type = TYPE_STRING;
  172. parm.method->required = NO;
  173. parm.method->answer = "average";
  174. p = G_malloc(1024);
  175. for (n = 0; menu[n].name; n++) {
  176. if (n)
  177. strcat(p, ",");
  178. else
  179. *p = 0;
  180. strcat(p, menu[n].name);
  181. }
  182. parm.method->options = p;
  183. parm.method->description = _("Neighborhood operation");
  184. parm.method->multiple = YES;
  185. parm.method->guisection = _("Neighborhood");
  186. parm.size = G_define_option();
  187. parm.size->key = "size";
  188. parm.size->type = TYPE_INTEGER;
  189. parm.size->required = NO;
  190. parm.size->description = _("Neighborhood size");
  191. parm.size->answer = "3";
  192. parm.size->guisection = _("Neighborhood");
  193. parm.title = G_define_option();
  194. parm.title->key = "title";
  195. parm.title->key_desc = "phrase";
  196. parm.title->type = TYPE_STRING;
  197. parm.title->required = NO;
  198. parm.title->description = _("Title for output raster map");
  199. parm.weight = G_define_standard_option(G_OPT_F_INPUT);
  200. parm.weight->key = "weight";
  201. parm.weight->required = NO;
  202. parm.weight->description = _("Text file containing weights");
  203. parm.gauss = G_define_option();
  204. parm.gauss->key = "gauss";
  205. parm.gauss->type = TYPE_DOUBLE;
  206. parm.gauss->required = NO;
  207. parm.gauss->description = _("Sigma (in cells) for Gaussian filter");
  208. parm.quantile = G_define_option();
  209. parm.quantile->key = "quantile";
  210. parm.quantile->type = TYPE_DOUBLE;
  211. parm.quantile->required = NO;
  212. parm.quantile->multiple = YES;
  213. parm.quantile->description = _("Quantile to calculate for method=quantile");
  214. parm.quantile->options = "0.0-1.0";
  215. flag.align = G_define_flag();
  216. flag.align->key = 'a';
  217. flag.align->description = _("Do not align output with the input");
  218. flag.circle = G_define_flag();
  219. flag.circle->key = 'c';
  220. flag.circle->description = _("Use circular neighborhood");
  221. flag.circle->guisection = _("Neighborhood");
  222. if (G_parser(argc, argv))
  223. exit(EXIT_FAILURE);
  224. sscanf(parm.size->answer, "%d", &ncb.nsize);
  225. if (ncb.nsize <= 0)
  226. G_fatal_error(_("Neighborhood size must be positive"));
  227. if (ncb.nsize % 2 == 0)
  228. G_fatal_error(_("Neighborhood size must be odd"));
  229. ncb.dist = ncb.nsize / 2;
  230. if (parm.weight->answer && flag.circle->answer)
  231. G_fatal_error(_("-%c and %s= are mutually exclusive"),
  232. flag.circle->key, parm.weight->key);
  233. if (parm.weight->answer && parm.gauss->answer)
  234. G_fatal_error(_("%s= and %s= are mutually exclusive"),
  235. parm.weight->key, parm.gauss->key);
  236. ncb.oldcell = parm.input->answer;
  237. if (!flag.align->answer) {
  238. Rast_get_cellhd(ncb.oldcell, "", &cellhd);
  239. G_get_window(&window);
  240. Rast_align_window(&window, &cellhd);
  241. Rast_set_window(&window);
  242. }
  243. nrows = Rast_window_rows();
  244. ncols = Rast_window_cols();
  245. /* open raster maps */
  246. in_fd = Rast_open_old(ncb.oldcell, "");
  247. map_type = Rast_get_map_type(in_fd);
  248. /* process the output maps */
  249. for (i = 0; parm.output->answers[i]; i++)
  250. ;
  251. num_outputs = i;
  252. for (i = 0; parm.method->answers[i]; i++)
  253. ;
  254. if (num_outputs != i)
  255. G_fatal_error(_("%s= and %s= must have the same number of values"),
  256. parm.output->key, parm.method->key);
  257. outputs = G_calloc(num_outputs, sizeof(struct output));
  258. /* read the weights */
  259. weights = 0;
  260. ncb.weights = NULL;
  261. ncb.mask = NULL;
  262. if (parm.weight->answer) {
  263. read_weights(parm.weight->answer);
  264. weights = 1;
  265. }
  266. else if (parm.gauss->answer) {
  267. gaussian_weights(atof(parm.gauss->answer));
  268. weights = 1;
  269. }
  270. copycolr = 0;
  271. have_weights_mask = 0;
  272. for (i = 0; i < num_outputs; i++) {
  273. struct output *out = &outputs[i];
  274. const char *output_name = parm.output->answers[i];
  275. const char *method_name = parm.method->answers[i];
  276. int method = find_method(method_name);
  277. RASTER_MAP_TYPE otype = output_type(map_type, weights, menu[method].otype);
  278. out->name = output_name;
  279. if (weights) {
  280. if (menu[method].method_w) {
  281. out->method_fn = NULL;
  282. out->method_fn_w = menu[method].method_w;
  283. }
  284. else {
  285. if (parm.weight->answer) {
  286. G_warning(_("Method %s not compatible with weighing window, using weight mask instead"),
  287. method_name);
  288. if (!have_weights_mask) {
  289. weights_mask();
  290. have_weights_mask = 1;
  291. }
  292. }
  293. else if (parm.gauss->answer) {
  294. G_warning(_("Method %s not compatible with Gaussian filter, using unweighed version instead"),
  295. method_name);
  296. }
  297. out->method_fn = menu[method].method;
  298. out->method_fn_w = NULL;
  299. }
  300. }
  301. else {
  302. out->method_fn = menu[method].method;
  303. out->method_fn_w = NULL;
  304. }
  305. out->copycolr = menu[method].copycolr;
  306. out->cat_names = menu[method].cat_names;
  307. if (out->copycolr)
  308. copycolr = 1;
  309. out->quantile = (parm.quantile->answer && parm.quantile->answers[i])
  310. ? atof(parm.quantile->answers[i])
  311. : 0;
  312. out->buf = Rast_allocate_d_buf();
  313. out->fd = Rast_open_new(output_name, otype);
  314. /* TODO: method=mode should propagate its type */
  315. /* get title, initialize the category and stat info */
  316. if (parm.title->answer)
  317. strcpy(out->title, parm.title->answer);
  318. else
  319. sprintf(out->title, "%dx%d neighborhood: %s of %s",
  320. ncb.nsize, ncb.nsize, menu[method].name, ncb.oldcell);
  321. }
  322. /* copy color table? */
  323. if (copycolr) {
  324. G_suppress_warnings(1);
  325. copycolr =
  326. (Rast_read_colors(ncb.oldcell, "", &colr) > 0);
  327. G_suppress_warnings(0);
  328. }
  329. /* allocate the cell buffers */
  330. allocate_bufs();
  331. /* initialize the cell bufs with 'dist' rows of the old cellfile */
  332. readrow = 0;
  333. for (row = 0; row < ncb.dist; row++)
  334. readcell(in_fd, readrow++, nrows, ncols);
  335. /* open the selection raster map */
  336. if (parm.selection->answer) {
  337. G_message(_("Opening selection map <%s>"), parm.selection->answer);
  338. selection_fd = Rast_open_old(parm.selection->answer, "");
  339. selection = Rast_allocate_null_buf();
  340. } else {
  341. selection_fd = -1;
  342. selection = NULL;
  343. }
  344. if (flag.circle->answer)
  345. circle_mask();
  346. values_w = NULL;
  347. values_w_tmp = NULL;
  348. if (weights) {
  349. values_w =
  350. (DCELL(*)[2]) G_malloc(ncb.nsize * ncb.nsize * 2 * sizeof(DCELL));
  351. values_w_tmp =
  352. (DCELL(*)[2]) G_malloc(ncb.nsize * ncb.nsize * 2 * sizeof(DCELL));
  353. }
  354. values = (DCELL *) G_malloc(ncb.nsize * ncb.nsize * sizeof(DCELL));
  355. values_tmp = (DCELL *) G_malloc(ncb.nsize * ncb.nsize * sizeof(DCELL));
  356. for (row = 0; row < nrows; row++) {
  357. G_percent(row, nrows, 2);
  358. readcell(in_fd, readrow++, nrows, ncols);
  359. if (selection)
  360. Rast_get_null_value_row(selection_fd, selection, row);
  361. for (col = 0; col < ncols; col++) {
  362. if (selection && selection[col]) {
  363. /* ncb.buf length is region row length + 2 * ncb.dist (eq. floor(neighborhood/2))
  364. * Thus original data start is shifted by ncb.dist! */
  365. for (i = 0; i < num_outputs; i++)
  366. outputs[i].buf[col] = ncb.buf[ncb.dist][col + ncb.dist];
  367. continue;
  368. }
  369. if (weights)
  370. n = gather_w(values, values_w, col);
  371. else
  372. n = gather(values, col);
  373. for (i = 0; i < num_outputs; i++) {
  374. struct output *out = &outputs[i];
  375. DCELL *rp = &out->buf[col];
  376. if (n == 0) {
  377. Rast_set_d_null_value(rp, 1);
  378. }
  379. else {
  380. if (out->method_fn_w) {
  381. memcpy(values_w_tmp, values_w, n * 2 * sizeof(DCELL));
  382. (*out->method_fn_w)(rp, values_w_tmp, n, &out->quantile);
  383. }
  384. else {
  385. memcpy(values_tmp, values, n * sizeof(DCELL));
  386. (*out->method_fn)(rp, values_tmp, n, &out->quantile);
  387. }
  388. }
  389. }
  390. }
  391. for (i = 0; i < num_outputs; i++) {
  392. struct output *out = &outputs[i];
  393. Rast_put_d_row(out->fd, out->buf);
  394. }
  395. }
  396. G_percent(row, nrows, 2);
  397. Rast_close(in_fd);
  398. if (selection)
  399. Rast_close(selection_fd);
  400. for (i = 0; i < num_outputs; i++) {
  401. Rast_close(outputs[i].fd);
  402. /* put out category info */
  403. null_cats(outputs[i].title);
  404. if (outputs[i].cat_names)
  405. outputs[i].cat_names();
  406. Rast_write_cats(outputs[i].name, &ncb.cats);
  407. if (copycolr && outputs[i].copycolr)
  408. Rast_write_colors(outputs[i].name, G_mapset(), &colr);
  409. Rast_short_history(outputs[i].name, "raster", &history);
  410. Rast_command_history(&history);
  411. Rast_write_history(outputs[i].name, &history);
  412. }
  413. exit(EXIT_SUCCESS);
  414. }