sweep.cpp 10 KB

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