main.c 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /****************************************************************************
  2. *
  3. * MODULE: r.quantile
  4. * AUTHOR(S): Glynn Clements <glynn gclements.plus.com> (original contributor),
  5. * PURPOSE: Compute 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 <stdio.h>
  14. #include <string.h>
  15. #include <math.h>
  16. #include <grass/gis.h>
  17. #include <grass/raster.h>
  18. #include <grass/glocale.h>
  19. /* TODO: replace long with either size_t or a guaranteed 64 bit integer */
  20. struct bin
  21. {
  22. size_t origin;
  23. DCELL min, max;
  24. size_t base, count;
  25. };
  26. static int rows, cols;
  27. static DCELL min, max;
  28. static int num_quants;
  29. static DCELL *quants;
  30. static int num_slots;
  31. static size_t *slots;
  32. static DCELL slot_size;
  33. /* total should be a 64bit integer */
  34. static unsigned long total;
  35. static size_t num_values;
  36. static unsigned short *slot_bins;
  37. static int num_bins;
  38. static struct bin *bins;
  39. static DCELL *values;
  40. static inline int get_slot(DCELL c)
  41. {
  42. int i = (int)floor((c - min) / slot_size);
  43. if (i < 0)
  44. i = 0;
  45. if (i > num_slots - 1)
  46. i = num_slots - 1;
  47. return i;
  48. }
  49. static inline double get_quantile(int n)
  50. {
  51. if (n >= num_quants)
  52. return (double)total + total;
  53. return (double)total * quants[n];
  54. }
  55. static void get_slot_counts(int infile)
  56. {
  57. DCELL *inbuf = Rast_allocate_d_buf();
  58. int row, col;
  59. G_message(_("Computing histogram"));
  60. total = 0;
  61. for (row = 0; row < rows; row++) {
  62. Rast_get_d_row(infile, inbuf, row);
  63. for (col = 0; col < cols; col++) {
  64. int i;
  65. if (Rast_is_d_null_value(&inbuf[col]))
  66. continue;
  67. i = get_slot(inbuf[col]);
  68. slots[i]++;
  69. total++;
  70. }
  71. G_percent(row, rows, 2);
  72. }
  73. G_percent(rows, rows, 2);
  74. G_free(inbuf);
  75. }
  76. static void initialize_bins(void)
  77. {
  78. int slot;
  79. double next;
  80. int bin = 0;
  81. size_t accum = 0;
  82. int quant = 0;
  83. G_message(_("Computing bins"));
  84. num_values = 0;
  85. next = get_quantile(quant);
  86. for (slot = 0; slot < num_slots; slot++) {
  87. size_t count = slots[slot];
  88. size_t accum2 = accum + count;
  89. if (accum2 > next ||
  90. (slot == num_slots - 1 && accum2 == next)) {
  91. struct bin *b = &bins[bin];
  92. slot_bins[slot] = ++bin;
  93. b->origin = accum;
  94. b->base = num_values;
  95. b->count = 0;
  96. b->min = min + slot_size * slot;
  97. b->max = min + slot_size * (slot + 1);
  98. while (accum2 > next)
  99. next = get_quantile(++quant);
  100. num_values += count;
  101. }
  102. accum = accum2;
  103. }
  104. num_bins = bin;
  105. G_debug(1, "Number of bins: %d", num_bins);
  106. G_debug(1, "Number of values: %lu", num_values);
  107. }
  108. static void fill_bins(int infile)
  109. {
  110. DCELL *inbuf = Rast_allocate_d_buf();
  111. int row, col;
  112. G_message(_("Binning data"));
  113. for (row = 0; row < rows; row++) {
  114. Rast_get_d_row(infile, inbuf, row);
  115. for (col = 0; col < cols; col++) {
  116. int i, bin;
  117. struct bin *b;
  118. if (Rast_is_d_null_value(&inbuf[col]))
  119. continue;
  120. i = get_slot(inbuf[col]);
  121. if (!slot_bins[i])
  122. continue;
  123. bin = slot_bins[i] - 1;
  124. b = &bins[bin];
  125. values[b->base + b->count++] = inbuf[col];
  126. }
  127. G_percent(row, rows, 2);
  128. }
  129. G_percent(rows, rows, 2);
  130. G_free(inbuf);
  131. }
  132. static int compare_dcell(const void *aa, const void *bb)
  133. {
  134. DCELL a = *(const DCELL *)aa;
  135. DCELL b = *(const DCELL *)bb;
  136. if (a < b)
  137. return -1;
  138. if (a > b)
  139. return 1;
  140. return 0;
  141. }
  142. static void sort_bins(void)
  143. {
  144. int bin;
  145. G_message(_("Sorting bins"));
  146. for (bin = 0; bin < num_bins; bin++) {
  147. struct bin *b = &bins[bin];
  148. qsort(&values[b->base], b->count, sizeof(DCELL), compare_dcell);
  149. }
  150. }
  151. static void compute_quantiles(int recode)
  152. {
  153. int bin = 0;
  154. double prev_v = min;
  155. int quant;
  156. G_message(_("Computing quantiles"));
  157. for (quant = 0; quant < num_quants; quant++) {
  158. struct bin *b = &bins[bin];
  159. double next = get_quantile(quant);
  160. double k, v;
  161. size_t i0, i1;
  162. for (; bin < num_bins; bin++) {
  163. b = &bins[bin];
  164. if (b->origin + b->count >= next)
  165. break;
  166. }
  167. if (bin < num_bins) {
  168. k = next - b->origin;
  169. i0 = (size_t)floor(k);
  170. i1 = (size_t)ceil(k);
  171. if (i0 > b->count - 1)
  172. i0 = b->count - 1;
  173. if (i1 > b->count - 1)
  174. i1 = b->count - 1;
  175. v = (i0 == i1)
  176. ? values[b->base + i0]
  177. : values[b->base + i0] * (i1 - k) +
  178. values[b->base + i1] * (k - i0);
  179. }
  180. else
  181. v = max;
  182. if (recode)
  183. fprintf(stdout, "%f:%f:%i\n", prev_v, v, quant + 1);
  184. else
  185. fprintf(stdout, "%d:%f:%f\n", quant, 100 * quants[quant], v);
  186. prev_v = v;
  187. }
  188. if (recode)
  189. printf("%f:%f:%i\n", prev_v, max, num_quants + 1);
  190. }
  191. int main(int argc, char *argv[])
  192. {
  193. struct GModule *module;
  194. struct
  195. {
  196. struct Option *input, *quant, *perc, *slots, *file;
  197. } opt;
  198. struct {
  199. struct Flag *r;
  200. } flag;
  201. int recode;
  202. int infile;
  203. struct FPRange range;
  204. G_gisinit(argv[0]);
  205. module = G_define_module();
  206. G_add_keyword(_("raster"));
  207. G_add_keyword(_("algebra"));
  208. G_add_keyword(_("statistics"));
  209. G_add_keyword(_("percentile"));
  210. G_add_keyword(_("quantile"));
  211. module->description = _("Compute quantiles using two passes.");
  212. opt.input = G_define_standard_option(G_OPT_R_INPUT);
  213. opt.quant = G_define_option();
  214. opt.quant->key = "quantiles";
  215. opt.quant->type = TYPE_INTEGER;
  216. opt.quant->required = NO;
  217. opt.quant->description = _("Number of quantiles");
  218. opt.quant->answer = "4";
  219. opt.perc = G_define_option();
  220. opt.perc->key = "percentiles";
  221. opt.perc->type = TYPE_DOUBLE;
  222. opt.perc->required = NO;
  223. opt.perc->multiple = YES;
  224. opt.perc->description = _("List of percentiles");
  225. opt.slots = G_define_option();
  226. opt.slots->key = "bins";
  227. opt.slots->type = TYPE_INTEGER;
  228. opt.slots->required = NO;
  229. opt.slots->description = _("Number of bins to use");
  230. opt.slots->answer = "1000000";
  231. opt.file = G_define_standard_option(G_OPT_F_OUTPUT);
  232. opt.file->key = "file";
  233. opt.file->required = NO;
  234. opt.file->description =
  235. _("Name for output file (if omitted or \"-\" output to stdout)");
  236. flag.r = G_define_flag();
  237. flag.r->key = 'r';
  238. flag.r->description = _("Generate recode rules based on quantile-defined intervals");
  239. if (G_parser(argc, argv))
  240. exit(EXIT_FAILURE);
  241. num_slots = atoi(opt.slots->answer);
  242. recode = flag.r->answer;
  243. if (opt.file->answer != NULL && strcmp(opt.file->answer, "-") != 0) {
  244. if (NULL == freopen(opt.file->answer, "w", stdout)) {
  245. G_fatal_error(_("Unable to open file <%s> for writing"), opt.file->answer);
  246. }
  247. }
  248. if (opt.perc->answer) {
  249. int i;
  250. for (i = 0; opt.perc->answers[i]; i++) ;
  251. num_quants = i;
  252. quants = G_calloc(num_quants, sizeof(DCELL));
  253. for (i = 0; i < num_quants; i++)
  254. quants[i] = atof(opt.perc->answers[i]) / 100;
  255. qsort(quants, num_quants, sizeof(DCELL), compare_dcell);
  256. }
  257. else {
  258. int i;
  259. num_quants = atoi(opt.quant->answer) - 1;
  260. quants = G_calloc(num_quants, sizeof(DCELL));
  261. for (i = 0; i < num_quants; i++)
  262. quants[i] = 1.0 * (i + 1) / (num_quants + 1);
  263. }
  264. if (num_quants > 65535)
  265. G_fatal_error(_("Too many quantiles"));
  266. infile = Rast_open_old(opt.input->answer, "");
  267. Rast_read_fp_range(opt.input->answer, "", &range);
  268. Rast_get_fp_range_min_max(&range, &min, &max);
  269. slots = G_calloc(num_slots, sizeof(size_t));
  270. slot_bins = G_calloc(num_slots, sizeof(unsigned short));
  271. slot_size = (max - min) / num_slots;
  272. rows = Rast_window_rows();
  273. cols = Rast_window_cols();
  274. get_slot_counts(infile);
  275. bins = G_calloc(num_quants, sizeof(struct bin));
  276. initialize_bins();
  277. G_free(slots);
  278. values = G_calloc(num_values, sizeof(DCELL));
  279. fill_bins(infile);
  280. Rast_close(infile);
  281. G_free(slot_bins);
  282. sort_bins();
  283. compute_quantiles(recode);
  284. return (EXIT_SUCCESS);
  285. }