main.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. struct bin
  20. {
  21. size_t origin;
  22. DCELL min, max;
  23. size_t base, count;
  24. };
  25. static int rows, cols;
  26. static DCELL min, max;
  27. static int num_quants;
  28. static DCELL *quants;
  29. static int num_slots;
  30. static size_t *slots;
  31. static DCELL slot_size;
  32. static grass_int64 total;
  33. static size_t num_values;
  34. static unsigned short *slot_bins;
  35. static int num_bins_alloc;
  36. static int num_bins_used;
  37. static struct bin *bins;
  38. static DCELL *values;
  39. static inline int get_slot(DCELL c)
  40. {
  41. int i = (int)floor((c - min) / slot_size);
  42. if (i < 0)
  43. i = 0;
  44. if (i > num_slots - 1)
  45. i = num_slots - 1;
  46. return i;
  47. }
  48. /* get zero-based rank for quantile */
  49. /* generic formula for one-based rank
  50. * rank = quant * (N + 1 - 2C) + C
  51. * with quant = quantile, N = number of values, C = constant
  52. * common values for C:
  53. * C = 0
  54. * rank = quant * (N + 1)
  55. * recommended by NIST (National Institute of Standards and Technology)
  56. * https://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm
  57. * C = 0.5
  58. * rank = quant * N + 0.5
  59. * Matlab
  60. * C = 1
  61. * rank = quant * (N - 1) + 1
  62. * numpy, R, MS Excel, ...
  63. * Noted as an alternative by NIST */
  64. static inline double get_quantile(int n)
  65. {
  66. double rnk;
  67. if (n >= num_quants) {
  68. /* stop condition for initialize_bins() */
  69. return (double)total + total;
  70. }
  71. rnk = quants[n] * (total - 1);
  72. if (rnk < 0)
  73. rnk = 0;
  74. if (rnk > total - 1)
  75. rnk = total - 1;
  76. return rnk;
  77. }
  78. static void get_slot_counts(int infile)
  79. {
  80. DCELL *inbuf = Rast_allocate_d_buf();
  81. int row, col;
  82. G_message(_("Computing histogram"));
  83. total = 0;
  84. for (row = 0; row < rows; row++) {
  85. Rast_get_d_row(infile, inbuf, row);
  86. for (col = 0; col < cols; col++) {
  87. int i;
  88. if (Rast_is_d_null_value(&inbuf[col]))
  89. continue;
  90. i = get_slot(inbuf[col]);
  91. slots[i]++;
  92. total++;
  93. }
  94. G_percent(row, rows, 2);
  95. }
  96. G_percent(rows, rows, 2);
  97. G_free(inbuf);
  98. }
  99. static void initialize_bins(void)
  100. {
  101. int slot;
  102. double next;
  103. int bin = 0;
  104. size_t accum = 0;
  105. int quant = 0;
  106. int use_next_slot = 0;
  107. G_message(_("Computing bins"));
  108. num_values = 0;
  109. next = get_quantile(quant);
  110. /* for a given quantile, two bins might be needed
  111. * if the index for this quantile is
  112. * > accumulated count of current bin
  113. * and
  114. * < accumulated count of next bin */
  115. for (slot = 0; slot < num_slots; slot++) {
  116. size_t count = slots[slot];
  117. size_t accum2 = accum + count;
  118. if (count > 0 &&
  119. (accum2 > next || use_next_slot) &&
  120. bin < num_bins_alloc) {
  121. struct bin *b = &bins[bin];
  122. slot_bins[slot] = ++bin;
  123. b->origin = accum;
  124. b->base = num_values;
  125. b->count = 0;
  126. b->min = min + slot_size * slot;
  127. b->max = min + slot_size * (slot + 1);
  128. use_next_slot = 0;
  129. if (accum2 - next < 1) {
  130. use_next_slot = 1;
  131. }
  132. else {
  133. while (accum2 > next)
  134. next = get_quantile(++quant);
  135. }
  136. num_values += count;
  137. }
  138. accum = accum2;
  139. }
  140. num_bins_used = bin;
  141. G_debug(1, "Number of used bins: %d", num_bins_used);
  142. G_debug(1, "Number of values: %lu", num_values);
  143. }
  144. static void fill_bins(int infile)
  145. {
  146. DCELL *inbuf = Rast_allocate_d_buf();
  147. int row, col;
  148. G_message(_("Binning data"));
  149. for (row = 0; row < rows; row++) {
  150. Rast_get_d_row(infile, inbuf, row);
  151. for (col = 0; col < cols; col++) {
  152. int i, bin;
  153. struct bin *b;
  154. if (Rast_is_d_null_value(&inbuf[col]))
  155. continue;
  156. i = get_slot(inbuf[col]);
  157. if (!slot_bins[i])
  158. continue;
  159. bin = slot_bins[i] - 1;
  160. b = &bins[bin];
  161. values[b->base + b->count++] = inbuf[col];
  162. }
  163. G_percent(row, rows, 2);
  164. }
  165. G_percent(rows, rows, 2);
  166. G_free(inbuf);
  167. }
  168. static int compare_dcell(const void *aa, const void *bb)
  169. {
  170. DCELL a = *(const DCELL *)aa;
  171. DCELL b = *(const DCELL *)bb;
  172. if (a < b)
  173. return -1;
  174. if (a > b)
  175. return 1;
  176. return 0;
  177. }
  178. static void sort_bins(void)
  179. {
  180. int bin;
  181. G_message(_("Sorting bins"));
  182. for (bin = 0; bin < num_bins_used; bin++) {
  183. struct bin *b = &bins[bin];
  184. qsort(&values[b->base], b->count, sizeof(DCELL), compare_dcell);
  185. }
  186. }
  187. static void compute_quantiles(int recode)
  188. {
  189. int bin = 0;
  190. double prev_v = min;
  191. int quant;
  192. G_message(_("Computing quantiles"));
  193. for (quant = 0; quant < num_quants; quant++) {
  194. struct bin *b = &bins[bin];
  195. double next = get_quantile(quant);
  196. double k, v;
  197. size_t i0, i1;
  198. for (; bin < num_bins_used; bin++) {
  199. b = &bins[bin];
  200. if (b->origin + b->count >= next)
  201. break;
  202. }
  203. if (bin < num_bins_used) {
  204. k = next - b->origin;
  205. i0 = (size_t)floor(k);
  206. i1 = (size_t)ceil(k);
  207. v = (i0 == i1)
  208. ? values[b->base + i0]
  209. : values[b->base + i0] * (i1 - k) +
  210. values[b->base + i1] * (k - i0);
  211. }
  212. else
  213. v = max;
  214. if (recode)
  215. fprintf(stdout, "%f:%f:%i\n", prev_v, v, quant + 1);
  216. else
  217. fprintf(stdout, "%d:%f:%f\n", quant, 100 * quants[quant], v);
  218. prev_v = v;
  219. }
  220. if (recode)
  221. printf("%f:%f:%i\n", prev_v, max, num_quants + 1);
  222. }
  223. int main(int argc, char *argv[])
  224. {
  225. struct GModule *module;
  226. struct
  227. {
  228. struct Option *input, *quant, *perc, *slots, *file;
  229. } opt;
  230. struct {
  231. struct Flag *r;
  232. } flag;
  233. int recode;
  234. int infile;
  235. struct FPRange range;
  236. int num_slots_max;
  237. G_gisinit(argv[0]);
  238. module = G_define_module();
  239. G_add_keyword(_("raster"));
  240. G_add_keyword(_("algebra"));
  241. G_add_keyword(_("statistics"));
  242. G_add_keyword(_("percentile"));
  243. G_add_keyword(_("quantile"));
  244. module->description = _("Compute quantiles using two passes.");
  245. opt.input = G_define_standard_option(G_OPT_R_INPUT);
  246. opt.quant = G_define_option();
  247. opt.quant->key = "quantiles";
  248. opt.quant->type = TYPE_INTEGER;
  249. opt.quant->required = NO;
  250. opt.quant->description = _("Number of quantiles");
  251. opt.quant->answer = "4";
  252. opt.perc = G_define_option();
  253. opt.perc->key = "percentiles";
  254. opt.perc->type = TYPE_DOUBLE;
  255. opt.perc->required = NO;
  256. opt.perc->multiple = YES;
  257. opt.perc->description = _("List of percentiles");
  258. opt.slots = G_define_option();
  259. opt.slots->key = "bins";
  260. opt.slots->type = TYPE_INTEGER;
  261. opt.slots->required = NO;
  262. opt.slots->description = _("Number of bins to use");
  263. opt.slots->answer = "1000000";
  264. opt.file = G_define_standard_option(G_OPT_F_OUTPUT);
  265. opt.file->key = "file";
  266. opt.file->required = NO;
  267. opt.file->description =
  268. _("Name for output file (if omitted or \"-\" output to stdout)");
  269. flag.r = G_define_flag();
  270. flag.r->key = 'r';
  271. flag.r->description = _("Generate recode rules based on quantile-defined intervals");
  272. if (G_parser(argc, argv))
  273. exit(EXIT_FAILURE);
  274. num_slots = atoi(opt.slots->answer);
  275. recode = flag.r->answer;
  276. if (opt.file->answer != NULL && strcmp(opt.file->answer, "-") != 0) {
  277. if (NULL == freopen(opt.file->answer, "w", stdout)) {
  278. G_fatal_error(_("Unable to open file <%s> for writing"), opt.file->answer);
  279. }
  280. }
  281. if (opt.perc->answer) {
  282. int i;
  283. for (i = 0; opt.perc->answers[i]; i++) ;
  284. num_quants = i;
  285. quants = G_calloc(num_quants, sizeof(DCELL));
  286. for (i = 0; i < num_quants; i++)
  287. quants[i] = atof(opt.perc->answers[i]) / 100;
  288. qsort(quants, num_quants, sizeof(DCELL), compare_dcell);
  289. }
  290. else {
  291. int i;
  292. num_quants = atoi(opt.quant->answer) - 1;
  293. quants = G_calloc(num_quants, sizeof(DCELL));
  294. for (i = 0; i < num_quants; i++)
  295. quants[i] = 1.0 * (i + 1) / (num_quants + 1);
  296. }
  297. if (num_quants > 65535)
  298. G_fatal_error(_("Too many quantiles"));
  299. infile = Rast_open_old(opt.input->answer, "");
  300. Rast_read_fp_range(opt.input->answer, "", &range);
  301. Rast_get_fp_range_min_max(&range, &min, &max);
  302. rows = Rast_window_rows();
  303. cols = Rast_window_cols();
  304. /* minimum 1000 values per slot to reduce memory consumption */
  305. num_slots_max = ((size_t)rows * cols) / 1000;
  306. if (num_slots_max < 1)
  307. num_slots_max = 1;
  308. if (num_slots > num_slots_max) {
  309. G_message(_("Reducing number of bins from %d to %d"),
  310. num_slots, num_slots_max);
  311. num_slots = num_slots_max;
  312. }
  313. slots = G_calloc(num_slots, sizeof(size_t));
  314. slot_bins = G_calloc(num_slots, sizeof(unsigned short));
  315. slot_size = (max - min) / num_slots;
  316. get_slot_counts(infile);
  317. /* sometimes two bins are needed to calculate a quantile */
  318. num_bins_alloc = num_quants * 2;
  319. bins = G_calloc(num_bins_alloc, sizeof(struct bin));
  320. initialize_bins();
  321. G_free(slots);
  322. values = G_calloc(num_values, sizeof(DCELL));
  323. fill_bins(infile);
  324. Rast_close(infile);
  325. G_free(slot_bins);
  326. sort_bins();
  327. compute_quantiles(recode);
  328. return (EXIT_SUCCESS);
  329. }