sweep.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /****************************************************************************
  2. *
  3. * MODULE: r.terraflow
  4. *
  5. * COPYRIGHT (C) 2007 Laura Toma
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. *****************************************************************************/
  18. #include <stdlib.h>
  19. #include <assert.h>
  20. #include <stdio.h>
  21. #include <unistd.h>
  22. #include <string.h>
  23. #include <grass/iostream/ami.h>
  24. #include "option.h"
  25. #include "stats.h"
  26. #include "sweep.h"
  27. #include "common.h"
  28. #include "weightWindow.h"
  29. #include "nodata.h"
  30. #include "sortutils.h"
  31. /*
  32. #define CHECKPARAM //output the parameters during sweeping
  33. #define CHECK_WEIGHTS //output weights as computed
  34. #define SWEEP_PRINT_PQSIZE //output priority queue size during sweeping
  35. #define CHECK_MEMORY //enables printing available memory in between steps
  36. */
  37. /* frequency; used to print progress dots */
  38. static const int DOT_CYCLE = 50;
  39. static const int PQSIZE_CYCLE = 100;
  40. /* globals in common.H
  41. extern statsRecorder *stats; stats file
  42. extern userOptions *opt; command-line options
  43. extern struct Cell_head *region; header of the region
  44. extern dimension_type nrows, ncols;
  45. */
  46. /* SELECT FLOW DATA STRUCTURE */
  47. #ifdef IM_PQUEUE
  48. typedef pqheap_t1<flowStructure> FLOW_DATASTR;
  49. #endif
  50. #ifdef EM_PQUEUE
  51. typedef em_pqueue<flowStructure, flowPriority> FLOW_DATASTR;
  52. #endif
  53. #ifdef EMPQ_ADAPTIVE
  54. typedef EMPQueueAdaptive<flowStructure, flowPriority> FLOW_DATASTR;
  55. #endif
  56. /* defined in this module */
  57. void pushFlow(const sweepItem& swit, const flowValue &flow,
  58. FLOW_DATASTR* flowpq, const weightWindow &weight);
  59. /* ------------------------------------------------------------*/
  60. sweepOutput::sweepOutput() {
  61. i = (dimension_type) nodataType::ELEVATION_NODATA;
  62. j = (dimension_type) nodataType::ELEVATION_NODATA;
  63. accu = (flowaccumulation_type) nodataType::ELEVATION_NODATA;
  64. #ifdef OUTPUT_TCI
  65. tci = (tci_type) nodataType::ELEVATION_NODATA;
  66. #endif
  67. };
  68. /* ------------------------------------------------------------ */
  69. /* computes output parameters of cell (i,j) given the flow value, the
  70. elevation of that cell and the weights of that cell; */
  71. void
  72. sweepOutput::compute(elevation_type elev,
  73. dimension_type i_crt, dimension_type j_crt,
  74. const flowValue &flow,
  75. const weightWindow &weight,
  76. const elevation_type nodata) {
  77. float correct_tci; /* this the correct value of tci; we're going to
  78. truncate this on current precision tci_type set by user in types.H*/
  79. assert(elev != nodata);
  80. assert(flow.get() >= 0);
  81. assert(weight.sumweight >= 0 && weight.sumcontour >= 0);
  82. i = i_crt;
  83. j = j_crt;
  84. if (weight.sumweight == 0 || weight.sumcontour == 0) {
  85. accu = (flowaccumulation_type)nodata;
  86. #ifdef OUTPUT_TCI
  87. tci = (tci_type)nodata;
  88. #endif
  89. } else {
  90. accu = flow.get();
  91. #ifdef OUTPUT_TCI
  92. correct_tci = log(flow.get()*weight.dx()*weight.dy()/weight.totalContour());
  93. /* assert(correct_tci > 0); //is this true? */
  94. /* there is no need for this warning. tci can be negative if the flow is small. */
  95. /* if (correct_tci < 0) {
  96. fprintf(stderr, "warning: tci negative, [flow=%f,dx=%f,dy=%f,cont=%f]\n",
  97. flow.get(), weight.dx(), weight.dy(), weight.totalContour());
  98. }
  99. */
  100. tci = (tci_type)correct_tci;
  101. #endif
  102. }
  103. return;
  104. }
  105. FLOW_DATASTR*
  106. initializePQ() {
  107. stats->comment("sweep:initialize flow data structure", opt->verbose);
  108. FLOW_DATASTR *flowpq;
  109. #ifdef IM_PQUEUE
  110. stats->comment("FLOW_DATASTRUCTURE: in-memory pqueue");
  111. flowpq = new FLOW_DATASTR(PQ_SIZE);
  112. char buf[1024];
  113. sprintf(buf, "initialized to %.2fMB\n", (float)PQ_SIZE / (1<<20));
  114. *stats << buf;
  115. #endif
  116. #ifdef EM_PQUEUE
  117. stats->comment("FLOW_DATASTRUCTURE: ext-memory pqueue");
  118. flowpq = new FLOW_DATASTR(nrows * ncols);
  119. #endif
  120. #ifdef EMPQ_ADAPTIVE
  121. if (opt->verbose) stats->comment("FLOW_DATASTRUCTURE: adaptive pqueue");
  122. flowpq = new FLOW_DATASTR();
  123. #endif
  124. return flowpq;
  125. }
  126. #define INIT_PRINT_PROGRESS() \
  127. long out_frequency, pqsize_frequency; \
  128. out_frequency = nrows*ncols / DOT_CYCLE; \
  129. pqsize_frequency = nrows*ncols / PQSIZE_CYCLE; \
  130. assert(out_frequency); \
  131. assert(pqsize_frequency);
  132. #define PRINT_PROGRESS(k) \
  133. if ((k) % out_frequency == 0) { \
  134. fprintf(stderr,"."); \
  135. fflush(stderr); \
  136. };
  137. #ifdef SWEEP_PRINT_PQSIZE
  138. #define PRINT_PQSIZE(k,flowpq) \
  139. if ((k) % pqsize_frequency == 0) { \
  140. fprintf(stderr," %ld ", (long)(flowpq)->size()); \
  141. fflush(stderr); \
  142. }
  143. #else
  144. #define PRINT_PQSIZE(k,flowpq)
  145. #endif
  146. /***************************************************************/
  147. /* Read the points in order from the sweep stream and process them.
  148. If trustdir = 1 then trust and use the directions contained in the
  149. sweep stream. Otherwise push flow to all downslope neighbors and
  150. use the direction only for points without downslope neighbors. */
  151. /***************************************************************/
  152. AMI_STREAM<sweepOutput>*
  153. sweep(AMI_STREAM<sweepItem> *sweepstr, const flowaccumulation_type D8CUT,
  154. const int trustdir) {
  155. flowPriority prio;
  156. flowValue flow;
  157. sweepItem* crtpoint;
  158. AMI_err ae;
  159. flowStructure x;
  160. long nitems;
  161. Rtimer rt;
  162. AMI_STREAM<sweepOutput>* outstr;
  163. /* INIT_PRINT_PROGRESS(); */
  164. rt_start(rt);
  165. assert(sweepstr);
  166. *stats << "sweeping\n";
  167. fprintf(stderr, "sweeping: ");
  168. /* create and initialize flow data structure */
  169. FLOW_DATASTR *flowpq;
  170. flowpq = initializePQ();
  171. /* create output stream */
  172. outstr = new AMI_STREAM<sweepOutput>();
  173. /* initialize weights and output */
  174. weightWindow weight(region->ew_res, region->ns_res);
  175. sweepOutput output;
  176. nitems = sweepstr->stream_len();
  177. #ifndef NDEBUG
  178. flowPriority prevprio = flowPriority(SHRT_MAX); /* XXX */
  179. #endif
  180. /* scan the sweep stream */
  181. ae = sweepstr->seek(0);
  182. assert(ae == AMI_ERROR_NO_ERROR);
  183. for (long k = 0; k < nitems; k++) {
  184. /* cout << k << endl; cout.flush(); */
  185. /* read next sweepItem = (prio, elevwin, topoRankwin, dir) */
  186. ae = sweepstr->read_item(&crtpoint);
  187. if (ae != AMI_ERROR_NO_ERROR) {
  188. fprintf(stderr, "sweep: k=%ld: cannot read next item..\n", k);
  189. exit(1);
  190. }
  191. /* cout << "k=" << k << " prio =" << crtpoint->getPriority() << "\n"; */
  192. /* nodata points should not be in sweep stream */
  193. assert(!is_nodata(crtpoint->getElev()));
  194. #ifndef NDEBUG
  195. assert(crtpoint->getPriority() > prevprio); /* XXX */
  196. prevprio = crtpoint->getPriority(); /* XXX */
  197. #endif
  198. /* compute flow accumulation of current point; initial flow value
  199. is 1 */
  200. flowValue flowini((double)1);
  201. /* add flow which was pushed into current point by upslope
  202. neighbours */
  203. assert(flowpq->is_empty() ||
  204. (flowpq->min(x), x.getPriority() >= crtpoint->getPriority())); /* XXX */
  205. assert(flowpq->is_empty() != flowpq->min(x)); /* XXX */
  206. if (flowpq->min(x) && ((prio=x.getPriority()) == crtpoint->getPriority())) {
  207. flowpq->extract_all_min(x);
  208. /* cout << "EXTRACT: " << x << endl; */
  209. flow = x.getValue();
  210. flow = flow + flowini;
  211. } else {
  212. flow = flowini;
  213. }
  214. assert(flowpq->is_empty() ||
  215. (flowpq->min(x), x.getPriority() > crtpoint->getPriority())); /* XXX */
  216. /* compute weights of current point given its direction */
  217. if (flow > D8CUT) {
  218. /* consider just the dominant direction */
  219. weight.makeD8(crtpoint->getI(), crtpoint->getJ(),
  220. crtpoint->getElevWindow(), crtpoint->getDir(), trustdir);
  221. } else {
  222. /* consider multiple flow directions */
  223. weight.compute(crtpoint->getI(), crtpoint->getJ(),
  224. crtpoint->getElevWindow(), crtpoint->getDir(), trustdir);
  225. }
  226. /* distribute the flow to its downslope neighbours */
  227. pushFlow(*crtpoint, flow, flowpq, weight);
  228. /* compute parameters */
  229. output.compute(crtpoint->getElev(), crtpoint->getI(), crtpoint->getJ(),
  230. flow, weight, nodataType::ELEVATION_NODATA);
  231. #ifdef CHECKPARAM
  232. printf("%7ld: (%5d, %5d, %5d) flow: %7.3f, weights:[",
  233. k, crtpoint->getElev(), crtpoint->getI(),crtpoint->getJ(),
  234. flow.get());
  235. for (int l=0;l<9;l++) printf("%2.1f ",weight.get(l));
  236. cout <<"] ";
  237. cout << output << "\n";
  238. #endif
  239. /* write output to sweep output stream */
  240. ae = outstr->write_item(output);
  241. assert(ae == AMI_ERROR_NO_ERROR);
  242. /* PRINT_PROGRESS(k); */
  243. /* PRINT_PQSIZE(k, flowpq); */
  244. G_percent(k, nitems, 2);
  245. } /* for k */
  246. G_percent(1, 1, 2); /* finish it */
  247. *stats << "sweeping done\n";
  248. char buf[1024];
  249. sprintf(buf, "pqsize = %ld \n", (long)flowpq->size());
  250. *stats << buf;
  251. assert(outstr->stream_len() == nitems);
  252. delete flowpq;
  253. rt_stop(rt);
  254. stats->recordTime("sweeping", rt);
  255. stats->recordLength("sweep output stream", outstr);
  256. return outstr;
  257. }
  258. /***************************************************************/
  259. /* push flow to neighbors as indicated by flow direction and reflected
  260. by the weights of the neighbors; flow is the accumulated flow value
  261. of current point; The neighbours which receive flow from current
  262. point are inserted in the FLOW_DATASTR */
  263. /***************************************************************/
  264. void
  265. pushFlow(const sweepItem& swit, const flowValue &flow,
  266. FLOW_DATASTR *flowpq,
  267. const weightWindow &weight) {
  268. dimension_type i_crt, j_crt, i_neighb, j_neighb;
  269. short di, dj;
  270. elevation_type elev_crt, elev_neighb;
  271. toporank_type toporank_crt;
  272. assert(flow >= 0);
  273. /* get current coordinates, elevation, topological rank */
  274. i_crt = swit.getI();
  275. j_crt = swit.getJ();
  276. elev_crt = swit.getElev();
  277. toporank_crt = swit.getTopoRank();
  278. assert(!is_nodata(elev_crt));
  279. for (di = -1; di <= 1; di++) {
  280. for (dj = -1; dj <= 1; dj++) {
  281. if (weight.get(di,dj) > 0) {
  282. /* push flow to this neighbor */
  283. i_neighb = i_crt + di;
  284. j_neighb = j_crt + dj;
  285. elev_neighb = swit.getElev(di,dj);
  286. /*assert(IS_BOUNDARY(i_crt,j_crt,hdr) || elev_neighb !=hdr.get_nodata());*/
  287. /* it's not simple to check what nodata is on boundary, so we'll
  288. just assume directions are correct even if they point to nodata
  289. elevation values. */
  290. if (!is_nodata(elev_neighb)) {
  291. flowPriority prio(elev_neighb, swit.getTopoRank(di,dj),
  292. i_neighb, j_neighb);
  293. flowPriority prio_crt(elev_crt,toporank_crt, i_crt, j_crt);
  294. /* assert(prio >= prio_crt); */
  295. #if (defined WARNING_FLAG)
  296. if (prio < prio_crt) {
  297. printf("\n(row=%d,col=%d,ele=%d): ",
  298. i_crt, j_crt, elev_crt);
  299. cout << "attempt to push flow uphill\n";
  300. }
  301. #endif
  302. flowValue elt(weight.get(di,dj)*flow.get());
  303. flowStructure x(prio, elt);
  304. assert(x.getPriority() > swit.getPriority());
  305. flowpq->insert(x);
  306. /* cout << "INSERT: " << x << endl; */
  307. } /* if (!is_nodata(elev_neighb)) */
  308. }
  309. } /* for dj */
  310. } /* for di */
  311. return;
  312. }