main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /****************************************************************************
  2. *
  3. * MODULE: r.terraflow
  4. *
  5. * COPYRIGHT (C) 2007, 2010 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 <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <assert.h>
  22. #include <ctype.h>
  23. #include <time.h>
  24. #include <sys/types.h>
  25. #ifdef HAVE_STATVFS_H
  26. #include <sys/statvfs.h>
  27. #endif
  28. extern "C" {
  29. #include <grass/gis.h>
  30. #include <grass/raster.h>
  31. #include <grass/glocale.h>
  32. }
  33. #include "option.h"
  34. #include "common.h" /* declares the globals */
  35. #include "fill.h"
  36. #include "flow.h"
  37. #include "nodata.h"
  38. #include "grass2str.h"
  39. #include "water.h"
  40. #include "sortutils.h"
  41. /* globals: in common.H
  42. extern statsRecorder *stats;
  43. extern userOptions* opt;
  44. extern struct Cell_head region;
  45. */
  46. /* #define JUMP2FLOW */
  47. /* define it only if you want to skip the flow direction computation
  48. and jump directly to computing flow accumulation; the flowstream
  49. must exist in /STREAM_DIR/flowStream */
  50. /* ---------------------------------------------------------------------- */
  51. void
  52. parse_args(int argc, char *argv[]) {
  53. /* input elevation grid */
  54. struct Option *input_elev;
  55. input_elev = G_define_standard_option(G_OPT_R_ELEV);
  56. /* output filled elevation grid */
  57. struct Option *output_elev;
  58. output_elev = G_define_standard_option(G_OPT_R_OUTPUT);
  59. output_elev->key = "filled";
  60. output_elev->description= _("Name for output filled (flooded) elevation raster map");
  61. /* output direction grid */
  62. struct Option *output_dir;
  63. output_dir = G_define_standard_option(G_OPT_R_OUTPUT);
  64. output_dir->key = "direction";
  65. output_dir->description= _("Name for output flow direction raster map");
  66. /* output sinkwatershed grid */
  67. struct Option *output_watershed;
  68. output_watershed = G_define_standard_option(G_OPT_R_OUTPUT);
  69. output_watershed->key = "swatershed";
  70. output_watershed->description= _("Name for output sink-watershed raster map");
  71. /* output flow accumulation grid */
  72. struct Option *output_accu;
  73. output_accu = G_define_standard_option(G_OPT_R_OUTPUT);
  74. output_accu->key = "accumulation";
  75. output_accu->description= _("Name for output flow accumulation raster map");
  76. #ifdef OUTPUT_TCI
  77. struct Option *output_tci;
  78. output_tci = G_define_standard_option(G_OPT_R_OUTPUT);
  79. output_tci->key = "tci";
  80. output_tci->description=
  81. _("Name for output topographic convergence index (tci) raster map");
  82. #endif
  83. /* MFD/SFD flag */
  84. struct Flag *sfd_flag;
  85. sfd_flag = G_define_flag() ;
  86. sfd_flag->key = 's';
  87. sfd_flag->description= _("SFD (D8) flow (default is MFD)");
  88. /* D8CUT value*/
  89. struct Option *d8cut;
  90. d8cut = G_define_option();
  91. d8cut->key = "d8cut";
  92. d8cut->type = TYPE_DOUBLE;
  93. d8cut->required = NO;
  94. d8cut->label = _("Routing using SFD (D8) direction");
  95. d8cut->description =
  96. _("If flow accumulation is larger than this value it is routed using "
  97. "SFD (D8) direction (meaningfull only for MFD flow). "
  98. "If no answer is given it defaults to infinity.");
  99. /* main memory */
  100. struct Option *mem;
  101. mem = G_define_option() ;
  102. mem->key = "memory";
  103. mem->type = TYPE_INTEGER;
  104. mem->required = NO;
  105. mem->answer = "300"; /* 300MB default value */
  106. mem->description = _("Maximum runtime memory size (in MB)");
  107. /* temporary STREAM path */
  108. struct Option *streamdir;
  109. streamdir = G_define_option() ;
  110. streamdir->key = "stream_dir";
  111. streamdir->type = TYPE_STRING;
  112. streamdir->required = NO;
  113. //streamdir->answer = "";
  114. streamdir->description=
  115. _("Directory to hold temporary files (they can be large)");
  116. /* stats file */
  117. struct Option *stats_opt;
  118. stats_opt = G_define_option() ;
  119. stats_opt->key = "stats";
  120. stats_opt->type = TYPE_STRING;
  121. stats_opt->required = NO;
  122. stats_opt->description= _("Name of file containing runtime statistics");
  123. if (G_parser(argc, argv)) {
  124. exit (EXIT_FAILURE);
  125. }
  126. /* ************************* */
  127. assert(opt);
  128. opt->elev_grid = input_elev->answer;
  129. opt->filled_grid = output_elev->answer;
  130. opt->dir_grid = output_dir->answer;
  131. opt->watershed_grid = output_watershed->answer;
  132. opt->flowaccu_grid = output_accu->answer;
  133. #ifdef OUTPUT_TCI
  134. opt->tci_grid = output_tci->answer;
  135. #endif
  136. opt->d8 = sfd_flag->answer;
  137. if (!d8cut->answer) {
  138. opt->d8cut = MAX_ACCU;
  139. } else {
  140. opt->d8cut = atof(d8cut->answer);
  141. }
  142. opt->mem = atoi(mem->answer);
  143. if (!streamdir->answer) {
  144. const char *tmpdir = G_tempfile();
  145. if (G_mkdir(tmpdir) == -1)
  146. G_fatal_error(_("Unable to create temp dir"));
  147. opt->streamdir = G_store(tmpdir);
  148. }
  149. else
  150. opt->streamdir = streamdir->answer;
  151. opt->verbose = G_verbose() == G_verbose_max();
  152. opt->stats = stats_opt->answer;
  153. /* somebody should delete the options */
  154. }
  155. /* ---------------------------------------------------------------------- */
  156. /* check compatibility of map header and region header */
  157. void check_header(char* cellname) {
  158. const char *mapset;
  159. mapset = G_find_raster(cellname, "");
  160. if (mapset == NULL) {
  161. G_fatal_error(_("Raster map <%s> not found"), cellname);
  162. }
  163. /* read cell header */
  164. struct Cell_head cell_hd;
  165. Rast_get_cellhd (cellname, mapset, &cell_hd);
  166. /* check compatibility with module region */
  167. if (!((region->ew_res == cell_hd.ew_res)
  168. && (region->ns_res == cell_hd.ns_res))) {
  169. G_fatal_error(_("cell file %s resolution differs from current region"),
  170. cellname);
  171. } else {
  172. if (opt->verbose) {
  173. G_message(_("cell %s header compatible with region header"),
  174. cellname);
  175. fflush(stderr);
  176. }
  177. }
  178. /* check type of input elevation raster and check if precision is lost */
  179. RASTER_MAP_TYPE data_type;
  180. data_type = Rast_map_type(opt->elev_grid, mapset);
  181. #ifdef ELEV_SHORT
  182. G_verbose_message(_("Elevation stored as SHORT (%dB)"),
  183. sizeof(elevation_type));
  184. if (data_type == FCELL_TYPE) {
  185. G_warning(_("raster %s is of type FCELL_TYPE "
  186. "--precision may be lost."), opt->elev_grid);
  187. }
  188. if (data_type == DCELL_TYPE) {
  189. G_warning(_("raster %s is of type DCELL_TYPE "
  190. "--precision may be lost."), opt->elev_grid);
  191. }
  192. #endif
  193. #ifdef ELEV_FLOAT
  194. G_verbose_message( _("Elevation stored as FLOAT (%dB)"),
  195. sizeof(elevation_type));
  196. if (data_type == CELL_TYPE) {
  197. G_warning(_("raster %s is of type CELL_TYPE "
  198. "--you should use r.terraflow.short"), opt->elev_grid);
  199. }
  200. if (data_type == DCELL_TYPE) {
  201. G_warning(_("raster %s is of type DCELL_TYPE "
  202. "--precision may be lost."), opt->elev_grid);
  203. }
  204. #endif
  205. }
  206. /* ---------------------------------------------------------------------- */
  207. void check_args() {
  208. /* check if filled elevation grid name is valid */
  209. if (G_legal_filename (opt->filled_grid) < 0) {
  210. G_fatal_error(_("<%s> is an illegal file name"), opt->filled_grid);
  211. }
  212. /* check if output grid names are valid */
  213. if (G_legal_filename (opt->dir_grid) < 0) {
  214. G_fatal_error(_("<%s> is an illegal file name"), opt->dir_grid);
  215. }
  216. if (G_legal_filename (opt->filled_grid) < 0) {
  217. G_fatal_error(_("<%s> is an illegal file name"), opt->filled_grid);
  218. }
  219. if (G_legal_filename (opt->flowaccu_grid) < 0) {
  220. G_fatal_error(_("<%s> is an illegal file name"), opt->flowaccu_grid);
  221. }
  222. if (G_legal_filename (opt->watershed_grid) < 0) {
  223. G_fatal_error(_("<%s> is an illegal file name"), opt->watershed_grid);
  224. }
  225. #ifdef OUTPU_TCI
  226. if (G_legal_filename (opt->tci_grid) < 0) {
  227. G_fatal_error(_("<%s> is an illegal file name"), opt->tci_grid);
  228. }
  229. #endif
  230. /* check compatibility with region */
  231. check_header(opt->elev_grid);
  232. /* what else ? */
  233. }
  234. /* ---------------------------------------------------------------------- */
  235. void record_args(int argc, char **argv) {
  236. time_t t = time(NULL);
  237. char buf[BUFSIZ];
  238. if(t == (time_t)-1) {
  239. perror("time");
  240. exit(1);
  241. }
  242. #ifdef __MINGW32__
  243. strcpy(buf, ctime(&t));
  244. #else
  245. ctime_r(&t, buf);
  246. buf[24] = '\0';
  247. #endif
  248. stats->timestamp(buf);
  249. *stats << "Command Line: " << endl;
  250. for(int i=0; i<argc; i++) {
  251. *stats << argv[i] << " ";
  252. }
  253. *stats << endl;
  254. *stats << "input elevation grid: " << opt->elev_grid << "\n";
  255. *stats << "output (flooded) elevations grid: " << opt->filled_grid << "\n";
  256. *stats << "output directions grid: " << opt->dir_grid << "\n";
  257. *stats << "output sinkwatershed grid: " << opt->watershed_grid << "\n";
  258. *stats << "output accumulation grid: " << opt->flowaccu_grid << "\n";
  259. #ifdef OUTPUT_TCI
  260. *stats << "output tci grid: " << opt->tci_grid << "\n";
  261. #endif
  262. if (opt->d8) {
  263. stats ->comment("SFD (D8) flow direction");
  264. } else {
  265. stats->comment("MFD flow direction");
  266. }
  267. sprintf(buf, "D8CUT=%f", opt->d8cut);
  268. stats->comment(buf);
  269. size_t mm_size = (size_t) opt->mem << 20; /* (in bytes) */
  270. char tmp[100];
  271. formatNumber(tmp, mm_size);
  272. sprintf(buf, "Memory size: %s bytes", tmp);
  273. stats->comment(buf);
  274. }
  275. /* ---------------------------------------------------------------------- */
  276. void
  277. setFlowAccuColorTable(char* cellname) {
  278. struct Colors colors;
  279. const char *mapset;
  280. struct Range r;
  281. mapset = G_find_raster(cellname, "");
  282. if (mapset == NULL) {
  283. G_fatal_error (_("Raster map <%s> not found"), cellname);
  284. }
  285. if (Rast_read_range(cellname, mapset, &r) == -1) {
  286. G_fatal_error(_("cannot read range"));
  287. }
  288. /*fprintf(stderr, "%s range is: min=%d, max=%d\n", cellname, r.min, r.max);*/
  289. int v[6];
  290. v[0] = r.min;
  291. v[1] = 5;
  292. v[2] = 30;
  293. v[3] = 100;
  294. v[4] = 1000;
  295. v[5] = r.max;
  296. Rast_init_colors(&colors);
  297. Rast_add_c_color_rule(&v[0], 255,255,255, &v[1], 255,255,0, &colors);
  298. Rast_add_c_color_rule(&v[1], 255,255,0, &v[2], 0,255,255, &colors);
  299. Rast_add_c_color_rule(&v[2], 0,255,255, &v[3], 0,127,255, &colors);
  300. Rast_add_c_color_rule(&v[3], 0,127,255, &v[4], 0,0,255, &colors);
  301. Rast_add_c_color_rule(&v[4], 0,0,255, &v[5], 0,0,0, &colors);
  302. Rast_write_colors(cellname, mapset, &colors);
  303. Rast_free_colors(&colors);
  304. }
  305. /* ---------------------------------------------------------------------- */
  306. void
  307. setSinkWatershedColorTable(char* cellname) {
  308. struct Colors colors;
  309. const char *mapset;
  310. struct Range r;
  311. mapset = G_find_raster(cellname, "");
  312. if (mapset == NULL) {
  313. G_fatal_error (_("Raster map <%s> not found"), cellname);
  314. }
  315. if (Rast_read_range(cellname, mapset, &r) == -1) {
  316. G_fatal_error(_("cannot read range"));
  317. }
  318. Rast_init_colors(&colors);
  319. Rast_make_random_colors(&colors, 1, r.max);
  320. Rast_write_colors(cellname, mapset, &colors);
  321. Rast_free_colors(&colors);
  322. }
  323. /* print the largest interm file that will be generated during
  324. r.terraflow */
  325. void
  326. printMaxSortSize(long nodata_count) {
  327. char buf[BUFSIZ];
  328. long long fillmaxsize = (long long)nrows*ncols*sizeof(waterWindowType);
  329. long long flowmaxsize = (long long)(nrows*ncols - nodata_count)*sizeof(sweepItem);
  330. long long maxneed = (fillmaxsize > flowmaxsize) ? fillmaxsize: flowmaxsize;
  331. maxneed = 2*maxneed; /* need 2*N to sort */
  332. G_message( "total elements=%ld, nodata elements=%ld",
  333. (long)nrows*ncols, nodata_count);
  334. G_message( "largest temporary files: ");
  335. G_message( "\t\t FILL: %s [%d elements, %dB each]",
  336. formatNumber(buf, fillmaxsize),
  337. nrows * ncols, sizeof(waterWindowType));
  338. G_message( "\t\t FLOW: %s [%ld elements, %dB each]",
  339. formatNumber(buf, flowmaxsize),
  340. (long)(nrows * ncols - nodata_count), sizeof(sweepItem));
  341. G_message( "Will need at least %s space available in %s",
  342. formatNumber(buf, maxneed), /* need 2*N to sort */
  343. getenv(STREAM_TMPDIR));
  344. #ifdef HAVE_STATVFS_H
  345. fprintf(stderr, "Checking current space in %s: ", getenv(STREAM_TMPDIR));
  346. struct statvfs statbuf;
  347. statvfs(getenv(STREAM_TMPDIR), &statbuf);
  348. float avail = statbuf.f_bsize*statbuf.f_bavail;
  349. fprintf(stderr, "available %ld blocks x %ldB = %.0fB",
  350. (long)statbuf.f_bavail, statbuf.f_bsize, avail);
  351. if (avail > maxneed) {
  352. fprintf(stderr, ". OK.\n");
  353. } else {
  354. fprintf(stderr, ". Not enough space available.\n");
  355. exit(EXIT_FAILURE);
  356. }
  357. #endif
  358. }
  359. /* ---------------------------------------------------------------------- */
  360. int
  361. main(int argc, char *argv[]) {
  362. struct GModule *module;
  363. Rtimer rtTotal;
  364. char buf[BUFSIZ];
  365. /* initialize GIS library */
  366. G_gisinit(argv[0]);
  367. module = G_define_module();
  368. #ifdef ELEV_SHORT
  369. module->description = _("Flow computation for massive grids (integer version).");
  370. #endif
  371. #ifdef ELEV_FLOAT
  372. module->description = _("Flow computation for massive grids (float version).");
  373. #endif
  374. G_add_keyword(_("raster"));
  375. G_add_keyword(_("hydrology"));
  376. /* read user options; fill in global <opt> */
  377. opt = (userOptions*)malloc(sizeof(userOptions));
  378. assert(opt);
  379. region = (struct Cell_head*)malloc(sizeof(struct Cell_head));
  380. assert(region);
  381. parse_args(argc, argv);
  382. /* get the current region and dimensions */
  383. G_get_set_window(region);
  384. check_args();
  385. int nr = Rast_window_rows();
  386. int nc = Rast_window_cols();
  387. if ((nr > dimension_type_max) || (nc > dimension_type_max)) {
  388. G_fatal_error(_("[nrows=%d, ncols=%d] dimension_type overflow -- "
  389. "change dimension_type and recompile"), nr, nc);
  390. } else {
  391. nrows = (dimension_type)nr;
  392. ncols = (dimension_type)nc;
  393. }
  394. G_verbose_message( _("Region size is %d x %d"), nrows, ncols);
  395. /* check STREAM path (the place where intermediate STREAMs are placed) */
  396. sprintf(buf, "%s=%s",STREAM_TMPDIR, opt->streamdir);
  397. /* don't pass an automatic variable; putenv() isn't guaranteed to make a copy */
  398. putenv(G_store(buf));
  399. if (getenv(STREAM_TMPDIR) == NULL) {
  400. fprintf(stderr, "%s:", STREAM_TMPDIR);
  401. G_fatal_error("not set");
  402. } else {
  403. fprintf(stderr, "STREAM temporary files in %s ",
  404. getenv(STREAM_TMPDIR));
  405. fprintf(stderr, "(THESE INTERMEDIATE STREAMS WILL NOT BE DELETED IN CASE OF ABNORMAL TERMINATION OF THE PROGRAM. TO SAVE SPACE PLEASE DELETE THESE FILES MANUALLY!)\n");
  406. }
  407. if (opt->stats) {
  408. /* open the stats file */
  409. stats = new statsRecorder(opt->stats);
  410. record_args(argc, argv);
  411. {
  412. char buf[BUFSIZ];
  413. long grid_size = nrows * ncols;
  414. *stats << "region size = " << formatNumber(buf, grid_size) << " elts "
  415. << "(" << nrows << " rows x " << ncols << " cols)\n";
  416. stats->flush();
  417. }
  418. }
  419. /* set up STREAM memory manager */
  420. size_t mm_size = (size_t) opt->mem << 20; /* opt->mem is in MB */
  421. MM_manager.set_memory_limit(mm_size);
  422. if (opt->verbose) {
  423. MM_manager.warn_memory_limit();
  424. } else {
  425. MM_manager.ignore_memory_limit();
  426. }
  427. MM_manager.print_limit_mode();
  428. /* initialize nodata */
  429. nodataType::init();
  430. if (stats)
  431. *stats << "internal nodata value: " << nodataType::ELEVATION_NODATA << endl;
  432. /* start timing -- after parse_args, which are interactive */
  433. rt_start(rtTotal);
  434. #ifndef JUMP2FLOW
  435. /* read elevation into a stream */
  436. AMI_STREAM<elevation_type> *elstr=NULL;
  437. long nodata_count;
  438. elstr = cell2stream<elevation_type>(opt->elev_grid, elevation_type_max,
  439. &nodata_count);
  440. /* print the largest interm file that will be generated */
  441. printMaxSortSize(nodata_count);
  442. /* -------------------------------------------------- */
  443. /* compute flow direction and filled elevation (and watersheds) */
  444. AMI_STREAM<direction_type> *dirstr=NULL;
  445. AMI_STREAM<elevation_type> *filledstr=NULL;
  446. AMI_STREAM<waterWindowBaseType> *flowStream=NULL;
  447. AMI_STREAM<labelElevType> *labeledWater = NULL;
  448. flowStream=computeFlowDirections(elstr, filledstr, dirstr, labeledWater);
  449. delete elstr;
  450. /* write streams to GRASS raster maps */
  451. stream2_CELL(dirstr, nrows, ncols, opt->dir_grid);
  452. delete dirstr;
  453. #ifdef ELEV_SHORT
  454. stream2_CELL(filledstr, nrows, ncols, opt->filled_grid);
  455. #else
  456. stream2_CELL(filledstr, nrows, ncols, opt->filled_grid,true);
  457. #endif
  458. delete filledstr;
  459. stream2_CELL(labeledWater, nrows, ncols, labelElevTypePrintLabel(),
  460. opt->watershed_grid);
  461. setSinkWatershedColorTable(opt->watershed_grid);
  462. delete labeledWater;
  463. #else
  464. AMI_STREAM<waterWindowBaseType> *flowStream;
  465. char path[GPATH_MAX];
  466. sprintf(path, "%s/flowStream", streamdir->answer);
  467. flowStream = new AMI_STREAM<waterWindowBaseType>(path);
  468. fprintf(stderr, "flowStream opened: len=%d\n", flowStream->stream_len());
  469. fprintf(stderr, "jumping to flow accumulation computation\n");
  470. #endif
  471. /* -------------------------------------------------- */
  472. /* compute flow accumulation (and tci) */
  473. AMI_STREAM<sweepOutput> *outstr=NULL;
  474. computeFlowAccumulation(flowStream, outstr);
  475. /* delete flowStream -- deleted inside */
  476. /* write output stream to GRASS raster maps */
  477. #ifdef OUTPUT_TCI
  478. stream2_FCELL(outstr, nrows, ncols, printAccumulation(), printTci(),
  479. opt->flowaccu_grid, opt->tci_grid);
  480. #else
  481. stream2_FCELL(outstr, nrows, ncols, printAccumulation(), opt->flowaccu_grid);
  482. #endif
  483. setFlowAccuColorTable(opt->flowaccu_grid);
  484. delete outstr;
  485. rt_stop(rtTotal);
  486. if (stats) {
  487. stats->recordTime("Total running time: ", rtTotal);
  488. stats->timestamp("end");
  489. }
  490. G_done_msg(" ");
  491. /* free the globals */
  492. free(region);
  493. free(opt);
  494. if (stats)
  495. delete stats;
  496. return 0;
  497. }