main.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. /****************************************************************************
  2. *
  3. * MODULE: r.statistics3
  4. * AUTHOR(S): Glynn Clements <glynn gclements.plus.com> (original contributor),
  5. * PURPOSE: Compute category or object oriented quantiles using two passes
  6. *
  7. * This program is free software under the GNU General Public
  8. * License (>=v2). Read the file COPYING that comes with GRASS
  9. * for details.
  10. *
  11. *****************************************************************************/
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <math.h>
  15. #include <grass/gis.h>
  16. #include <grass/raster.h>
  17. #include <grass/glocale.h>
  18. #include <grass/spawn.h>
  19. #define MAX_CATS 1000
  20. struct bin
  21. {
  22. unsigned long origin;
  23. DCELL min, max;
  24. int base, count;
  25. };
  26. struct basecat
  27. {
  28. unsigned int *slots;
  29. unsigned long total;
  30. int num_values;
  31. unsigned char *slot_bins;
  32. int num_bins;
  33. struct bin *bins;
  34. DCELL *values;
  35. DCELL *quants;
  36. };
  37. static int num_quants;
  38. static DCELL *quants;
  39. static DCELL f_min, f_max;
  40. static int num_slots;
  41. static DCELL slot_size;
  42. static int rows, cols;
  43. static int min, max;
  44. static int num_cats;
  45. static struct basecat *basecats;
  46. static inline int get_slot(DCELL c)
  47. {
  48. int i = (int)floor((c - min) / slot_size);
  49. if (i < 0)
  50. i = 0;
  51. if (i > num_slots - 1)
  52. i = num_slots - 1;
  53. return i;
  54. }
  55. static inline double get_quantile(struct basecat *bc, int n)
  56. {
  57. return (double)bc->total * quants[n];
  58. }
  59. static void get_slot_counts(int basefile, int coverfile)
  60. {
  61. CELL *basebuf = Rast_allocate_c_buf();
  62. DCELL *coverbuf = Rast_allocate_d_buf();
  63. int row, col;
  64. G_message(_("Computing histograms"));
  65. for (row = 0; row < rows; row++) {
  66. Rast_get_c_row(basefile, basebuf, row);
  67. Rast_get_d_row(coverfile, coverbuf, row);
  68. for (col = 0; col < cols; col++) {
  69. struct basecat *bc;
  70. int i;
  71. if (Rast_is_c_null_value(&basebuf[col]))
  72. continue;
  73. if (Rast_is_d_null_value(&coverbuf[col]))
  74. continue;
  75. i = get_slot(coverbuf[col]);
  76. bc = &basecats[basebuf[col] - min];
  77. bc->slots[i]++;
  78. bc->total++;
  79. }
  80. G_percent(row, rows, 2);
  81. }
  82. G_percent(rows, rows, 2);
  83. G_free(basebuf);
  84. G_free(coverbuf);
  85. }
  86. static void initialize_bins(void)
  87. {
  88. int cat;
  89. G_message(_("Computing bins"));
  90. for (cat = 0; cat < num_cats; cat++) {
  91. struct basecat *bc = &basecats[cat];
  92. int slot;
  93. double next;
  94. int num_values = 0;
  95. int bin = 0;
  96. unsigned long accum = 0;
  97. int quant = 0;
  98. bc->bins = G_calloc(num_quants, sizeof(struct bin));
  99. bc->slot_bins = G_calloc(num_slots, sizeof(unsigned char));
  100. next = get_quantile(bc, quant);
  101. for (slot = 0; slot < num_slots; slot++) {
  102. unsigned int count = bc->slots[slot];
  103. unsigned long accum2 = accum + count;
  104. if (accum2 > next) {
  105. struct bin *b = &bc->bins[bin];
  106. bc->slot_bins[slot] = ++bin;
  107. b->origin = accum;
  108. b->base = num_values;
  109. b->count = 0;
  110. b->min = min + slot_size * slot;
  111. b->max = min + slot_size * (slot + 1);
  112. while (accum2 > next)
  113. next = get_quantile(bc, ++quant);
  114. num_values += count;
  115. }
  116. accum = accum2;
  117. }
  118. bc->num_values = num_values;
  119. bc->num_bins = bin;
  120. G_free(bc->slots);
  121. bc->values = G_calloc(num_values, sizeof(DCELL));
  122. }
  123. }
  124. static void fill_bins(int basefile, int coverfile)
  125. {
  126. CELL *basebuf = Rast_allocate_c_buf();
  127. DCELL *coverbuf = Rast_allocate_d_buf();
  128. int row, col;
  129. G_message(_("Binning data"));
  130. for (row = 0; row < rows; row++) {
  131. Rast_get_c_row(basefile, basebuf, row);
  132. Rast_get_d_row(coverfile, coverbuf, row);
  133. for (col = 0; col < cols; col++) {
  134. struct basecat *bc;
  135. int i, bin;
  136. struct bin *b;
  137. if (Rast_is_c_null_value(&basebuf[col]))
  138. continue;
  139. if (Rast_is_d_null_value(&coverbuf[col]))
  140. continue;
  141. i = get_slot(coverbuf[col]);
  142. bc = &basecats[basebuf[col] - min];
  143. if (!bc->slot_bins[i])
  144. continue;
  145. bin = bc->slot_bins[i] - 1;
  146. b = &bc->bins[bin];
  147. bc->values[b->base + b->count++] = coverbuf[col];
  148. }
  149. G_percent(row, rows, 2);
  150. }
  151. G_percent(rows, rows, 2);
  152. G_free(basebuf);
  153. G_free(coverbuf);
  154. }
  155. static int compare_dcell(const void *aa, const void *bb)
  156. {
  157. DCELL a = *(const DCELL *)aa;
  158. DCELL b = *(const DCELL *)bb;
  159. if (a < b)
  160. return -1;
  161. if (a > b)
  162. return 1;
  163. return 0;
  164. }
  165. static void sort_bins(void)
  166. {
  167. int cat;
  168. G_message(_("Sorting bins"));
  169. for (cat = 0; cat < num_cats; cat++) {
  170. struct basecat *bc = &basecats[cat];
  171. int bin;
  172. G_free(bc->slot_bins);
  173. for (bin = 0; bin < bc->num_bins; bin++) {
  174. struct bin *b = &bc->bins[bin];
  175. qsort(&bc->values[b->base], b->count, sizeof(DCELL), compare_dcell);
  176. }
  177. G_percent(cat, num_cats, 2);
  178. }
  179. G_percent(cat, num_cats, 2);
  180. }
  181. static void print_quantiles(void)
  182. {
  183. int cat;
  184. G_message(_("Printing quantiles"));
  185. for (cat = 0; cat < num_cats; cat++) {
  186. struct basecat *bc = &basecats[cat];
  187. int quant;
  188. for (quant = 0; quant < num_quants; quant++)
  189. printf("%d:%d:%f:%f\n", min + cat, quant, 100 * quants[quant], bc->quants[quant]);
  190. }
  191. }
  192. static void compute_quantiles(void)
  193. {
  194. int cat;
  195. G_message(_("Computing quantiles"));
  196. for (cat = 0; cat < num_cats; cat++) {
  197. struct basecat *bc = &basecats[cat];
  198. struct bin *b = &bc->bins[0];
  199. int quant;
  200. bc->quants = G_malloc(num_quants * sizeof(DCELL));
  201. for (quant = 0; quant < num_quants; quant++) {
  202. double next = get_quantile(bc, quant);
  203. double k, v;
  204. int i0, i1;
  205. while (b->origin + b->count < next)
  206. b++;
  207. k = next - b->origin;
  208. i0 = (int)floor(k);
  209. i1 = (int)ceil(k);
  210. v = (i0 == i1)
  211. ? bc->values[b->base + i0]
  212. : bc->values[b->base + i0] * (i1 - k) + bc->values[b->base + i1] * (k - i0);
  213. bc->quants[quant] = v;
  214. }
  215. }
  216. }
  217. static void do_reclass(const char *basemap, char **outputs)
  218. {
  219. const char *tempfile = G_tempfile();
  220. char *input_arg = G_malloc(strlen(basemap) + 7);
  221. char *rules_arg = G_malloc(strlen(tempfile) + 7);
  222. int quant;
  223. G_message(_("Generating reclass maps"));
  224. sprintf(input_arg, "input=%s", basemap);
  225. sprintf(rules_arg, "rules=%s", tempfile);
  226. for (quant = 0; quant < num_quants; quant++) {
  227. const char *output = outputs[quant];
  228. char *output_arg = G_malloc(strlen(output) + 8);
  229. FILE *fp;
  230. int cat;
  231. sprintf(output_arg, "output=%s", output);
  232. fp = fopen(tempfile, "w");
  233. if (!fp)
  234. G_fatal_error(_("Unable to open temporary file"));
  235. for (cat = 0; cat < num_cats; cat++)
  236. fprintf(fp, "%d = %d %f\n", min + cat, min + cat, basecats[cat].quants[quant]);
  237. fclose(fp);
  238. G_spawn("r.reclass", "r.reclass", input_arg, output_arg, rules_arg, NULL);
  239. }
  240. remove(tempfile);
  241. }
  242. static void do_output(int base_fd, char **outputs, const char *covermap)
  243. {
  244. int *out_fd = G_malloc(num_quants * sizeof(int));
  245. CELL *base_buf = Rast_allocate_c_buf();
  246. DCELL *out_buf = Rast_allocate_d_buf();
  247. const char *mapset = G_mapset();
  248. struct Colors colors;
  249. int have_colors;
  250. int quant;
  251. int row, col;
  252. G_message(_("Writing output maps"));
  253. for (quant = 0; quant < num_quants; quant++) {
  254. const char *output = outputs[quant];
  255. out_fd[quant] = Rast_open_fp_new(output);
  256. }
  257. have_colors = Rast_read_colors(covermap, "", &colors) > 0;
  258. for (row = 0; row < rows; row++) {
  259. Rast_get_c_row(base_fd, base_buf, row);
  260. for (quant = 0; quant < num_quants; quant++) {
  261. for (col = 0; col < cols; col++)
  262. if (Rast_is_c_null_value(&base_buf[col]))
  263. Rast_set_d_null_value(&out_buf[col], 1);
  264. else
  265. out_buf[col] = basecats[base_buf[col] - min].quants[quant];
  266. Rast_put_d_row(out_fd[quant], out_buf);
  267. }
  268. G_percent(row, rows, 2);
  269. }
  270. G_percent(row, rows, 2);
  271. for (quant = 0; quant < num_quants; quant++) {
  272. Rast_close(out_fd[quant]);
  273. if (have_colors)
  274. Rast_write_colors(outputs[quant], mapset, &colors);
  275. }
  276. }
  277. int main(int argc, char *argv[])
  278. {
  279. struct GModule *module;
  280. struct
  281. {
  282. struct Option *quant, *perc, *slots, *basemap, *covermap, *output;
  283. } opt;
  284. struct {
  285. struct Flag *r, *p;
  286. } flag;
  287. const char *basemap, *covermap;
  288. char **outputs;
  289. int reclass, print;
  290. int cover_fd, base_fd;
  291. struct Range range;
  292. struct FPRange fprange;
  293. int i;
  294. G_gisinit(argv[0]);
  295. module = G_define_module();
  296. G_add_keyword(_("raster"));
  297. G_add_keyword(_("statistics"));
  298. module->description = _("Compute category quantiles using two passes.");
  299. opt.basemap = G_define_standard_option(G_OPT_R_BASE);
  300. opt.covermap = G_define_standard_option(G_OPT_R_COVER);
  301. opt.quant = G_define_option();
  302. opt.quant->key = "quantiles";
  303. opt.quant->type = TYPE_INTEGER;
  304. opt.quant->required = NO;
  305. opt.quant->description = _("Number of quantiles");
  306. opt.perc = G_define_option();
  307. opt.perc->key = "percentiles";
  308. opt.perc->type = TYPE_DOUBLE;
  309. opt.perc->multiple = YES;
  310. opt.perc->description = _("List of percentiles");
  311. opt.perc->answer = "50";
  312. opt.slots = G_define_option();
  313. opt.slots->key = "bins";
  314. opt.slots->type = TYPE_INTEGER;
  315. opt.slots->required = NO;
  316. opt.slots->description = _("Number of bins to use");
  317. opt.slots->answer = "1000";
  318. opt.output = G_define_standard_option(G_OPT_R_OUTPUT);
  319. opt.output->description = _("Resultant raster map(s)");
  320. opt.output->required = NO;
  321. opt.output->multiple = YES;
  322. flag.r = G_define_flag();
  323. flag.r->key = 'r';
  324. flag.r->description =
  325. _("Create reclass map with statistics as category labels");
  326. flag.p = G_define_flag();
  327. flag.p->key = 'p';
  328. flag.p->description =
  329. _("Don't create output maps; just print statistics");
  330. if (G_parser(argc, argv))
  331. exit(EXIT_FAILURE);
  332. basemap = opt.basemap->answer;
  333. covermap = opt.covermap->answer;
  334. outputs = opt.output->answers;
  335. reclass = flag.r->answer;
  336. print = flag.p->answer;
  337. if (!print && !opt.output->answers)
  338. G_fatal_error(_("Either -p or output= must be given"));
  339. if (print && opt.output->answers)
  340. G_fatal_error(_("-p and output= are mutually exclusive"));
  341. num_slots = atoi(opt.slots->answer);
  342. if (opt.quant->answer) {
  343. num_quants = atoi(opt.quant->answer) - 1;
  344. quants = G_calloc(num_quants, sizeof(DCELL));
  345. for (i = 0; i < num_quants; i++)
  346. quants[i] = 1.0 * (i + 1) / (num_quants + 1);
  347. }
  348. else {
  349. for (i = 0; opt.perc->answers[i]; i++)
  350. ;
  351. num_quants = i;
  352. quants = G_calloc(num_quants, sizeof(DCELL));
  353. for (i = 0; i < num_quants; i++)
  354. quants[i] = atof(opt.perc->answers[i]) / 100;
  355. qsort(quants, num_quants, sizeof(DCELL), compare_dcell);
  356. }
  357. if (opt.output->answer) {
  358. for (i = 0; opt.output->answers[i]; i++)
  359. ;
  360. if (i != num_quants)
  361. G_fatal_error(_("Number of quantiles (%d) does not match number of output maps (%d)"),
  362. num_quants, i);
  363. }
  364. base_fd = Rast_open_old(basemap, "");
  365. cover_fd = Rast_open_old(covermap, "");
  366. if (Rast_map_is_fp(basemap, "") != 0)
  367. G_fatal_error(_("The base map must be an integer (CELL) map"));
  368. if (Rast_read_range(basemap, "", &range) < 0)
  369. G_fatal_error(_("Unable to read range of base map <%s>"), basemap);
  370. Rast_get_range_min_max(&range, &min, &max);
  371. num_cats = max - min + 1;
  372. if (num_cats > MAX_CATS)
  373. G_fatal_error(_("Base map <%s> has too many categories (max: %d)"),
  374. basemap, MAX_CATS);
  375. Rast_read_fp_range(covermap, "", &fprange);
  376. Rast_get_fp_range_min_max(&fprange, &f_min, &f_max);
  377. slot_size = (f_max - f_min) / num_slots;
  378. basecats = G_calloc(num_cats, sizeof(struct basecat));
  379. for (i = 0; i < num_cats; i++)
  380. basecats[i].slots = G_calloc(num_slots, sizeof(unsigned int));
  381. rows = Rast_window_rows();
  382. cols = Rast_window_cols();
  383. get_slot_counts(base_fd, cover_fd);
  384. initialize_bins();
  385. fill_bins(base_fd, cover_fd);
  386. sort_bins();
  387. compute_quantiles();
  388. if (print)
  389. print_quantiles();
  390. else if (reclass)
  391. do_reclass(basemap, outputs);
  392. else
  393. do_output(base_fd, outputs, covermap);
  394. Rast_close(cover_fd);
  395. Rast_close(base_fd);
  396. return (EXIT_SUCCESS);
  397. }