main.cpp 18 KB

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