main.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. /***************************************************************************
  2. *
  3. * MODULE: r.proj
  4. *
  5. * AUTHOR(S): Martin Schroeder
  6. * University of Heidelberg
  7. * Dept. of Geography
  8. * emes@geo0.geog.uni-heidelberg.de
  9. *
  10. * (With the help of a lot of existing GRASS sources, in
  11. * particular v.proj)
  12. *
  13. * PURPOSE: r.proj converts a map to a new geographic projection. It reads a
  14. * map from a different location, projects it and write it out
  15. * to the current location. The projected data is resampled with
  16. * one of three different methods: nearest neighbor, bilinear and
  17. * cubic convolution.
  18. *
  19. * COPYRIGHT: (C) 2001, 2011 by the GRASS Development Team
  20. *
  21. * This program is free software under the GNU General Public
  22. * License (>=v2). Read the file COPYING that comes with GRASS
  23. * for details.
  24. *
  25. * Changes
  26. * Morten Hulden <morten@untamo.net>, Aug 2000:
  27. * - aborts if input map is outside current location.
  28. * - can handle projections (conic, azimuthal etc) where
  29. * part of the map may fall into areas where south is
  30. * upward and east is leftward.
  31. * - avoids passing location edge coordinates to PROJ
  32. * (they may be invalid in some projections).
  33. * - output map will be clipped to borders of the current region.
  34. * - output map cell edges and centers will coinside with those
  35. * of the current region.
  36. * - output map resolution (unless changed explicitly) will
  37. * match (exactly) the resolution of the current region.
  38. * - if the input map is smaller than the current region, the
  39. * output map will only cover the overlapping area.
  40. * - if the input map is larger than the current region, only the
  41. * needed amount of memory will be allocated for the projection
  42. *
  43. * Bugfixes 20050328: added floor() before (int) typecasts to in avoid
  44. * assymetrical rounding errors. Added missing offset outcellhd.ew_res/2
  45. * to initial xcoord for each row in main projection loop (we want to project
  46. * center of cell, not border).
  47. *
  48. * Glynn Clements 2006: Use G_interp_* functions, modified
  49. * version of r.proj which uses a tile cache instead of loading the
  50. * entire map into memory.
  51. * Markus Metz 2010: lanczos and lanczos fallback interpolation methods
  52. *****************************************************************************/
  53. #include <stdio.h>
  54. #include <stdlib.h>
  55. #include <string.h>
  56. #include <unistd.h>
  57. #include <grass/gis.h>
  58. #include <grass/raster.h>
  59. #include <grass/gprojects.h>
  60. #include <grass/glocale.h>
  61. #include "r.proj.h"
  62. /* modify this table to add new methods */
  63. struct menu menu[] = {
  64. {p_nearest, "nearest", "nearest neighbor"},
  65. {p_bilinear, "bilinear", "bilinear interpolation"},
  66. {p_cubic, "bicubic", "bicubic interpolation"},
  67. {p_lanczos, "lanczos", "lanczos filter"},
  68. {p_bilinear_f, "bilinear_f", "bilinear interpolation with fallback"},
  69. {p_cubic_f, "bicubic_f", "bicubic interpolation with fallback"},
  70. {p_lanczos_f, "lanczos_f", "lanczos filter with fallback"},
  71. {NULL, NULL, NULL}
  72. };
  73. static char *make_ipol_list(void);
  74. static char *make_ipol_desc(void);
  75. int main(int argc, char **argv)
  76. {
  77. char *mapname, /* ptr to name of output layer */
  78. *setname, /* ptr to name of input mapset */
  79. *ipolname; /* name of interpolation method */
  80. int fdi, /* input map file descriptor */
  81. fdo, /* output map file descriptor */
  82. method, /* position of method in table */
  83. permissions, /* mapset permissions */
  84. cell_type, /* output celltype */
  85. cell_size, /* size of a cell in bytes */
  86. row, col, /* counters */
  87. irows, icols, /* original rows, cols */
  88. orows, ocols, have_colors, /* Input map has a colour table */
  89. overwrite, /* Overwrite */
  90. curr_proj; /* output projection (see gis.h) */
  91. void *obuffer; /* buffer that holds one output row */
  92. struct cache *ibuffer; /* buffer that holds the input map */
  93. func interpolate; /* interpolation routine */
  94. double xcoord2, /* temporary x coordinates */
  95. ycoord2, /* temporary y coordinates */
  96. onorth, osouth, /* save original border coords */
  97. oeast, owest, inorth, isouth, ieast, iwest;
  98. char north_str[30], south_str[30], east_str[30], west_str[30];
  99. struct Colors colr; /* Input map colour table */
  100. struct History history;
  101. struct pj_info iproj, /* input map proj parameters */
  102. oproj; /* output map proj parameters */
  103. struct Key_Value *in_proj_info, /* projection information of */
  104. *in_unit_info, /* input and output mapsets */
  105. *out_proj_info, *out_unit_info;
  106. struct GModule *module;
  107. struct Flag *list, /* list files in source location */
  108. *nocrop, /* don't crop output map */
  109. *print_bounds, /* print output bounds and exit */
  110. *gprint_bounds; /* same but print shell style */
  111. struct Option *imapset, /* name of input mapset */
  112. *inmap, /* name of input layer */
  113. *inlocation, /* name of input location */
  114. *outmap, /* name of output layer */
  115. *indbase, /* name of input database */
  116. *interpol, /* interpolation method:
  117. nearest neighbor, bilinear, cubic */
  118. *memory, /* amount of memory for cache */
  119. *res; /* resolution of target map */
  120. struct Cell_head incellhd, /* cell header of input map */
  121. outcellhd; /* and output map */
  122. G_gisinit(argv[0]);
  123. module = G_define_module();
  124. G_add_keyword(_("raster"));
  125. G_add_keyword(_("projection"));
  126. G_add_keyword(_("transformation"));
  127. module->description =
  128. _("Re-projects a raster map from given location to the current location.");
  129. inlocation = G_define_standard_option(G_OPT_M_LOCATION);
  130. inlocation->required = YES;
  131. inlocation->label = _("Location containing input raster map");
  132. inlocation->guisection = _("Source");
  133. imapset = G_define_standard_option(G_OPT_M_MAPSET);
  134. imapset->label = _("Mapset containing input raster map");
  135. imapset->description = _("Default: name of current mapset");
  136. imapset->guisection = _("Source");
  137. inmap = G_define_standard_option(G_OPT_R_INPUT);
  138. inmap->description = _("Name of input raster map to re-project");
  139. inmap->required = NO;
  140. inmap->guisection = _("Source");
  141. indbase = G_define_standard_option(G_OPT_M_DBASE);
  142. indbase->label = _("Path to GRASS database of input location");
  143. outmap = G_define_standard_option(G_OPT_R_OUTPUT);
  144. outmap->required = NO;
  145. outmap->description = _("Name for output raster map (default: same as 'input')");
  146. outmap->guisection = _("Target");
  147. ipolname = make_ipol_list();
  148. interpol = G_define_option();
  149. interpol->key = "method";
  150. interpol->type = TYPE_STRING;
  151. interpol->required = NO;
  152. interpol->answer = "nearest";
  153. interpol->options = ipolname;
  154. interpol->description = _("Interpolation method to use");
  155. interpol->guisection = _("Target");
  156. interpol->descriptions = make_ipol_desc();
  157. memory = G_define_option();
  158. memory->key = "memory";
  159. memory->type = TYPE_INTEGER;
  160. memory->required = NO;
  161. memory->answer = "300";
  162. memory->label = _("Maximum memory to be used (in MB)");
  163. memory->description = _("Cache size for raster rows");
  164. res = G_define_option();
  165. res->key = "resolution";
  166. res->type = TYPE_DOUBLE;
  167. res->required = NO;
  168. res->description = _("Resolution of output raster map");
  169. res->guisection = _("Target");
  170. list = G_define_flag();
  171. list->key = 'l';
  172. list->description = _("List raster maps in input mapset and exit");
  173. list->guisection = _("Print");
  174. nocrop = G_define_flag();
  175. nocrop->key = 'n';
  176. nocrop->description = _("Do not perform region cropping optimization");
  177. print_bounds = G_define_flag();
  178. print_bounds->key = 'p';
  179. print_bounds->description =
  180. _("Print input map's bounds in the current projection and exit");
  181. print_bounds->guisection = _("Print");
  182. gprint_bounds = G_define_flag();
  183. gprint_bounds->key = 'g';
  184. gprint_bounds->description =
  185. _("Print input map's bounds in the current projection and exit (shell style)");
  186. gprint_bounds->guisection = _("Print");
  187. /* The parser checks if the map already exists in current mapset,
  188. we switch out the check and do it
  189. in the module after the parser */
  190. overwrite = G_check_overwrite(argc, argv);
  191. if (G_parser(argc, argv))
  192. exit(EXIT_FAILURE);
  193. /* get the method */
  194. for (method = 0; (ipolname = menu[method].name); method++)
  195. if (strcmp(ipolname, interpol->answer) == 0)
  196. break;
  197. if (!ipolname)
  198. G_fatal_error(_("<%s=%s> unknown %s"),
  199. interpol->key, interpol->answer, interpol->key);
  200. interpolate = menu[method].method;
  201. mapname = outmap->answer ? outmap->answer : inmap->answer;
  202. if (mapname && !list->answer && !overwrite &&
  203. !print_bounds->answer && !gprint_bounds->answer &&
  204. G_find_raster(mapname, G_mapset()))
  205. G_fatal_error(_("option <%s>: <%s> exists. To overwrite, use the --overwrite flag"),
  206. "output", mapname);
  207. setname = imapset->answer ? imapset->answer : G_store(G_mapset());
  208. if (strcmp(inlocation->answer, G_location()) == 0 &&
  209. (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0))
  210. #if 0
  211. G_fatal_error(_("Input and output locations can not be the same"));
  212. #else
  213. G_warning(_("Input and output locations are the same"));
  214. #endif
  215. G_get_window(&outcellhd);
  216. if (gprint_bounds->answer && !print_bounds->answer)
  217. print_bounds->answer = gprint_bounds->answer;
  218. curr_proj = G_projection();
  219. /* Get projection info for output mapset */
  220. if ((out_proj_info = G_get_projinfo()) == NULL)
  221. G_fatal_error(_("Unable to get projection info of output raster map"));
  222. if ((out_unit_info = G_get_projunits()) == NULL)
  223. G_fatal_error(_("Unable to get projection units of output raster map"));
  224. if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0)
  225. G_fatal_error(_("Unable to get projection key values of output raster map"));
  226. /* Change the location */
  227. G_create_alt_env();
  228. G_setenv_nogisrc("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase());
  229. G_setenv_nogisrc("LOCATION_NAME", inlocation->answer);
  230. permissions = G_mapset_permissions(setname);
  231. if (permissions < 0) /* can't access mapset */
  232. G_fatal_error(_("Mapset <%s> in input location <%s> - %s"),
  233. setname, inlocation->answer,
  234. permissions == 0 ? _("permission denied")
  235. : _("not found"));
  236. /* if requested, list the raster maps in source location - MN 5/2001 */
  237. if (list->answer) {
  238. int i;
  239. char **list;
  240. G_verbose_message(_("Checking location <%s> mapset <%s>"),
  241. inlocation->answer, setname);
  242. list = G_list(G_ELEMENT_RASTER, G_getenv_nofatal("GISDBASE"),
  243. G_getenv_nofatal("LOCATION_NAME"), setname);
  244. for (i = 0; list[i]; i++) {
  245. fprintf(stdout, "%s\n", list[i]);
  246. }
  247. fflush(stdout);
  248. exit(EXIT_SUCCESS); /* leave r.proj after listing */
  249. }
  250. if (!inmap->answer)
  251. G_fatal_error(_("Required parameter <%s> not set"), inmap->key);
  252. if (!G_find_raster(inmap->answer, setname))
  253. G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"),
  254. inmap->answer, inlocation->answer, setname);
  255. /* Read input map colour table */
  256. have_colors = Rast_read_colors(inmap->answer, setname, &colr);
  257. /* Get projection info for input mapset */
  258. if ((in_proj_info = G_get_projinfo()) == NULL)
  259. G_fatal_error(_("Unable to get projection info of input map"));
  260. if ((in_unit_info = G_get_projunits()) == NULL)
  261. G_fatal_error(_("Unable to get projection units of input map"));
  262. if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0)
  263. G_fatal_error(_("Unable to get projection key values of input map"));
  264. G_free_key_value(in_proj_info);
  265. G_free_key_value(in_unit_info);
  266. G_free_key_value(out_proj_info);
  267. G_free_key_value(out_unit_info);
  268. if (G_verbose() > G_verbose_std())
  269. pj_print_proj_params(&iproj, &oproj);
  270. /* this call causes r.proj to read the entire map into memeory */
  271. Rast_get_cellhd(inmap->answer, setname, &incellhd);
  272. Rast_set_input_window(&incellhd);
  273. if (G_projection() == PROJECTION_XY)
  274. G_fatal_error(_("Unable to work with unprojected data (xy location)"));
  275. /* Save default borders so we can show them later */
  276. inorth = incellhd.north;
  277. isouth = incellhd.south;
  278. ieast = incellhd.east;
  279. iwest = incellhd.west;
  280. irows = incellhd.rows;
  281. icols = incellhd.cols;
  282. onorth = outcellhd.north;
  283. osouth = outcellhd.south;
  284. oeast = outcellhd.east;
  285. owest = outcellhd.west;
  286. orows = outcellhd.rows;
  287. ocols = outcellhd.cols;
  288. if (print_bounds->answer) {
  289. G_message(_("Input map <%s@%s> in location <%s>:"),
  290. inmap->answer, setname, inlocation->answer);
  291. outcellhd.north = -1e9;
  292. outcellhd.south = 1e9;
  293. outcellhd.east = -1e9;
  294. outcellhd.west = 1e9;
  295. bordwalk_edge(&incellhd, &outcellhd, &iproj, &oproj);
  296. inorth = outcellhd.north;
  297. isouth = outcellhd.south;
  298. ieast = outcellhd.east;
  299. iwest = outcellhd.west;
  300. G_format_northing(inorth, north_str, curr_proj);
  301. G_format_northing(isouth, south_str, curr_proj);
  302. G_format_easting(ieast, east_str, curr_proj);
  303. G_format_easting(iwest, west_str, curr_proj);
  304. if (gprint_bounds->answer) {
  305. fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n",
  306. north_str, south_str, west_str, east_str, irows, icols);
  307. }
  308. else {
  309. fprintf(stdout, "Source cols: %d\n", icols);
  310. fprintf(stdout, "Source rows: %d\n", irows);
  311. fprintf(stdout, "Local north: %s\n", north_str);
  312. fprintf(stdout, "Local south: %s\n", south_str);
  313. fprintf(stdout, "Local west: %s\n", west_str);
  314. fprintf(stdout, "Local east: %s\n", east_str);
  315. }
  316. exit(EXIT_SUCCESS);
  317. }
  318. /* Cut non-overlapping parts of input map */
  319. if (!nocrop->answer)
  320. bordwalk(&outcellhd, &incellhd, &oproj, &iproj);
  321. /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */
  322. /* (should probably be a factor based on input and output resolution) */
  323. incellhd.north += 2 * incellhd.ns_res;
  324. incellhd.east += 2 * incellhd.ew_res;
  325. incellhd.south -= 2 * incellhd.ns_res;
  326. incellhd.west -= 2 * incellhd.ew_res;
  327. if (incellhd.north > inorth)
  328. incellhd.north = inorth;
  329. if (incellhd.east > ieast)
  330. incellhd.east = ieast;
  331. if (incellhd.south < isouth)
  332. incellhd.south = isouth;
  333. if (incellhd.west < iwest)
  334. incellhd.west = iwest;
  335. Rast_set_input_window(&incellhd);
  336. /* And switch back to original location */
  337. G_switch_env();
  338. /* Adjust borders of output map */
  339. if (!nocrop->answer)
  340. bordwalk(&incellhd, &outcellhd, &iproj, &oproj);
  341. #if 0
  342. outcellhd.west = outcellhd.south = HUGE_VAL;
  343. outcellhd.east = outcellhd.north = -HUGE_VAL;
  344. for (row = 0; row < incellhd.rows; row++) {
  345. ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd);
  346. for (col = 0; col < incellhd.cols; col++) {
  347. xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd);
  348. pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj);
  349. if (xcoord1 > outcellhd.east)
  350. outcellhd.east = xcoord1;
  351. if (ycoord1 > outcellhd.north)
  352. outcellhd.north = ycoord1;
  353. if (xcoord1 < outcellhd.west)
  354. outcellhd.west = xcoord1;
  355. if (ycoord1 < outcellhd.south)
  356. outcellhd.south = ycoord1;
  357. }
  358. }
  359. #endif
  360. if (res->answer != NULL) /* set user defined resolution */
  361. outcellhd.ns_res = outcellhd.ew_res = atof(res->answer);
  362. G_adjust_Cell_head(&outcellhd, 0, 0);
  363. Rast_set_output_window(&outcellhd);
  364. G_message(" ");
  365. G_message(_("Input:"));
  366. G_message(_("Cols: %d (%d)"), incellhd.cols, icols);
  367. G_message(_("Rows: %d (%d)"), incellhd.rows, irows);
  368. G_message(_("North: %f (%f)"), incellhd.north, inorth);
  369. G_message(_("South: %f (%f)"), incellhd.south, isouth);
  370. G_message(_("West: %f (%f)"), incellhd.west, iwest);
  371. G_message(_("East: %f (%f)"), incellhd.east, ieast);
  372. G_message(_("EW-res: %f"), incellhd.ew_res);
  373. G_message(_("NS-res: %f"), incellhd.ns_res);
  374. G_message(" ");
  375. G_message(_("Output:"));
  376. G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols);
  377. G_message(_("Rows: %d (%d)"), outcellhd.rows, orows);
  378. G_message(_("North: %f (%f)"), outcellhd.north, onorth);
  379. G_message(_("South: %f (%f)"), outcellhd.south, osouth);
  380. G_message(_("West: %f (%f)"), outcellhd.west, owest);
  381. G_message(_("East: %f (%f)"), outcellhd.east, oeast);
  382. G_message(_("EW-res: %f"), outcellhd.ew_res);
  383. G_message(_("NS-res: %f"), outcellhd.ns_res);
  384. G_message(" ");
  385. /* open and read the relevant parts of the input map and close it */
  386. G_switch_env();
  387. Rast_set_input_window(&incellhd);
  388. fdi = Rast_open_old(inmap->answer, setname);
  389. cell_type = Rast_get_map_type(fdi);
  390. ibuffer = readcell(fdi, memory->answer);
  391. Rast_close(fdi);
  392. G_switch_env();
  393. Rast_set_output_window(&outcellhd);
  394. if (strcmp(interpol->answer, "nearest") == 0) {
  395. fdo = Rast_open_new(mapname, cell_type);
  396. obuffer = (CELL *) Rast_allocate_output_buf(cell_type);
  397. }
  398. else {
  399. fdo = Rast_open_fp_new(mapname);
  400. cell_type = FCELL_TYPE;
  401. obuffer = (FCELL *) Rast_allocate_output_buf(cell_type);
  402. }
  403. cell_size = Rast_cell_size(cell_type);
  404. xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
  405. ycoord2 = outcellhd.north - (outcellhd.ns_res / 2);
  406. G_important_message(_("Projecting..."));
  407. for (row = 0; row < outcellhd.rows; row++) {
  408. /* obufptr = obuffer */;
  409. G_percent(row, outcellhd.rows - 1, 2);
  410. #if 0
  411. /* parallelization does not always work,
  412. * segfaults in the interpolation functions
  413. * can happen */
  414. #pragma omp parallel for schedule (static)
  415. #endif
  416. for (col = 0; col < outcellhd.cols; col++) {
  417. void *obufptr = (void *)((const unsigned char *)obuffer + col * cell_size);
  418. double xcoord1 = xcoord2 + (col) * outcellhd.ew_res;
  419. double ycoord1 = ycoord2;
  420. /* project coordinates in output matrix to */
  421. /* coordinates in input matrix */
  422. if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0)
  423. Rast_set_null_value(obufptr, 1, cell_type);
  424. else {
  425. /* convert to row/column indices of input matrix */
  426. /* column index in input matrix */
  427. double col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res;
  428. /* row index in input matrix */
  429. double row_idx = (incellhd.north - ycoord1) / incellhd.ns_res;
  430. /* and resample data point */
  431. interpolate(ibuffer, obufptr, cell_type,
  432. col_idx, row_idx, &incellhd);
  433. }
  434. /* obufptr = G_incr_void_ptr(obufptr, cell_size); */
  435. }
  436. Rast_put_row(fdo, obuffer, cell_type);
  437. xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
  438. ycoord2 -= outcellhd.ns_res;
  439. }
  440. Rast_close(fdo);
  441. release_cache(ibuffer);
  442. if (have_colors > 0) {
  443. Rast_write_colors(mapname, G_mapset(), &colr);
  444. Rast_free_colors(&colr);
  445. }
  446. Rast_short_history(mapname, "raster", &history);
  447. Rast_command_history(&history);
  448. Rast_write_history(mapname, &history);
  449. G_done_msg(" ");
  450. exit(EXIT_SUCCESS);
  451. }
  452. char *make_ipol_list(void)
  453. {
  454. int size = 0;
  455. int i;
  456. char *buf;
  457. for (i = 0; menu[i].name; i++)
  458. size += strlen(menu[i].name) + 1;
  459. buf = G_malloc(size);
  460. *buf = '\0';
  461. for (i = 0; menu[i].name; i++) {
  462. if (i)
  463. strcat(buf, ",");
  464. strcat(buf, menu[i].name);
  465. }
  466. return buf;
  467. }
  468. char *make_ipol_desc(void)
  469. {
  470. int size = 0;
  471. int i;
  472. char *buf;
  473. for (i = 0; menu[i].name; i++)
  474. size += strlen(menu[i].name) + strlen(menu[i].text) + 2;
  475. buf = G_malloc(size);
  476. *buf = '\0';
  477. for (i = 0; menu[i].name; i++) {
  478. if (i)
  479. strcat(buf, ";");
  480. strcat(buf, menu[i].name);
  481. strcat(buf, ";");
  482. strcat(buf, menu[i].text);
  483. }
  484. return buf;
  485. }