main.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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@ngb.se>, 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"},
  66. {p_cubic, "cubic", "cubic convolution"},
  67. {p_lanczos, "lanczos", "lanczos filter"},
  68. {p_bilinear_f, "bilinear_f", "bilinear with fallback"},
  69. {p_cubic_f, "cubic_f", "cubic convolution 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. *obufptr; /* column ptr in output buffer */
  93. struct cache *ibuffer; /* buffer that holds the input map */
  94. func interpolate; /* interpolation routine */
  95. double xcoord1, xcoord2, /* temporary x coordinates */
  96. ycoord1, ycoord2, /* temporary y coordinates */
  97. col_idx, /* column index in input matrix */
  98. row_idx, /* row index in input matrix */
  99. onorth, osouth, /* save original border coords */
  100. oeast, owest, inorth, isouth, ieast, iwest;
  101. char north_str[30], south_str[30], east_str[30], west_str[30];
  102. struct Colors colr; /* Input map colour table */
  103. struct History history;
  104. struct pj_info iproj, /* input map proj parameters */
  105. oproj; /* output map proj parameters */
  106. struct Key_Value *in_proj_info, /* projection information of */
  107. *in_unit_info, /* input and output mapsets */
  108. *out_proj_info, *out_unit_info;
  109. struct GModule *module;
  110. struct Flag *list, /* list files in source location */
  111. *nocrop, /* don't crop output map */
  112. *print_bounds, /* print output bounds and exit */
  113. *gprint_bounds; /* same but print shell style */
  114. struct Option *imapset, /* name of input mapset */
  115. *inmap, /* name of input layer */
  116. *inlocation, /* name of input location */
  117. *outmap, /* name of output layer */
  118. *indbase, /* name of input database */
  119. *interpol, /* interpolation method:
  120. nearest neighbor, bilinear, cubic */
  121. *memory, /* amount of memory for cache */
  122. *res; /* resolution of target map */
  123. struct Cell_head incellhd, /* cell header of input map */
  124. outcellhd; /* and output map */
  125. G_gisinit(argv[0]);
  126. module = G_define_module();
  127. G_add_keyword(_("raster"));
  128. G_add_keyword(_("projection"));
  129. G_add_keyword(_("transformation"));
  130. module->description =
  131. _("Re-projects a raster map from given location to the current location.");
  132. inmap = G_define_standard_option(G_OPT_R_INPUT);
  133. inmap->description = _("Name of input raster map to re-project");
  134. inmap->required = NO;
  135. inmap->guisection = _("Source");
  136. inlocation = G_define_option();
  137. inlocation->key = "location";
  138. inlocation->type = TYPE_STRING;
  139. inlocation->required = YES;
  140. inlocation->description = _("Location containing input raster map");
  141. inlocation->gisprompt = "old,location,location";
  142. inlocation->key_desc = "name";
  143. imapset = G_define_standard_option(G_OPT_M_MAPSET);
  144. imapset->label = _("Mapset containing input raster map");
  145. imapset->description = _("default: name of current mapset");
  146. imapset->guisection = _("Source");
  147. indbase = G_define_option();
  148. indbase->key = "dbase";
  149. indbase->type = TYPE_STRING;
  150. indbase->required = NO;
  151. indbase->description = _("Path to GRASS database of input location");
  152. indbase->gisprompt = "old,dbase,dbase";
  153. indbase->key_desc = "path";
  154. indbase->guisection = _("Source");
  155. outmap = G_define_standard_option(G_OPT_R_OUTPUT);
  156. outmap->required = NO;
  157. outmap->description = _("Name for output raster map (default: same as 'input')");
  158. outmap->guisection = _("Target");
  159. ipolname = make_ipol_list();
  160. interpol = G_define_option();
  161. interpol->key = "method";
  162. interpol->type = TYPE_STRING;
  163. interpol->required = NO;
  164. interpol->answer = "nearest";
  165. interpol->options = ipolname;
  166. interpol->description = _("Interpolation method to use");
  167. interpol->guisection = _("Target");
  168. interpol->descriptions = make_ipol_desc();
  169. memory = G_define_option();
  170. memory->key = "memory";
  171. memory->type = TYPE_INTEGER;
  172. memory->required = NO;
  173. memory->description = _("Cache size (MiB)");
  174. res = G_define_option();
  175. res->key = "resolution";
  176. res->type = TYPE_DOUBLE;
  177. res->required = NO;
  178. res->description = _("Resolution of output raster map");
  179. res->guisection = _("Target");
  180. list = G_define_flag();
  181. list->key = 'l';
  182. list->description = _("List raster maps in input location and exit");
  183. nocrop = G_define_flag();
  184. nocrop->key = 'n';
  185. nocrop->description = _("Do not perform region cropping optimization");
  186. print_bounds = G_define_flag();
  187. print_bounds->key = 'p';
  188. print_bounds->description =
  189. _("Print input map's bounds in the current projection and exit");
  190. print_bounds->guisection = _("Target");
  191. gprint_bounds = G_define_flag();
  192. gprint_bounds->key = 'g';
  193. gprint_bounds->description =
  194. _("Print input map's bounds in the current projection and exit (shell style)");
  195. gprint_bounds->guisection = _("Target");
  196. /* The parser checks if the map already exists in current mapset,
  197. we switch out the check and do it
  198. in the module after the parser */
  199. overwrite = G_check_overwrite(argc, argv);
  200. if (G_parser(argc, argv))
  201. exit(EXIT_FAILURE);
  202. /* get the method */
  203. for (method = 0; (ipolname = menu[method].name); method++)
  204. if (strcmp(ipolname, interpol->answer) == 0)
  205. break;
  206. if (!ipolname)
  207. G_fatal_error(_("<%s=%s> unknown %s"),
  208. interpol->key, interpol->answer, interpol->key);
  209. interpolate = menu[method].method;
  210. mapname = outmap->answer ? outmap->answer : inmap->answer;
  211. if (mapname && !list->answer && !overwrite &&
  212. G_find_raster(mapname, G_mapset()))
  213. G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname);
  214. setname = imapset->answer ? imapset->answer : G_store(G_mapset());
  215. if (strcmp(inlocation->answer, G_location()) == 0 &&
  216. (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0))
  217. #if 0
  218. G_fatal_error(_("Input and output locations can not be the same"));
  219. #else
  220. G_warning(_("Input and output locations are the same"));
  221. #endif
  222. G_get_window(&outcellhd);
  223. if(gprint_bounds->answer && !print_bounds->answer)
  224. print_bounds->answer = gprint_bounds->answer;
  225. curr_proj = G_projection();
  226. /* Get projection info for output mapset */
  227. if ((out_proj_info = G_get_projinfo()) == NULL)
  228. G_fatal_error(_("Unable to get projection info of output raster map"));
  229. if ((out_unit_info = G_get_projunits()) == NULL)
  230. G_fatal_error(_("Unable to get projection units of output raster map"));
  231. if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0)
  232. G_fatal_error(_("Unable to get projection key values of output raster map"));
  233. /* Change the location */
  234. G__create_alt_env();
  235. G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase());
  236. G__setenv("LOCATION_NAME", inlocation->answer);
  237. permissions = G__mapset_permissions(setname);
  238. if (permissions < 0) /* can't access mapset */
  239. G_fatal_error(_("Mapset <%s> in input location <%s> - %s"),
  240. setname, inlocation->answer,
  241. permissions == 0 ? _("permission denied")
  242. : _("not found"));
  243. /* if requested, list the raster maps in source location - MN 5/2001 */
  244. if (list->answer) {
  245. int i;
  246. char **list;
  247. G_verbose_message(_("Checking location <%s> mapset <%s>"),
  248. inlocation->answer, setname);
  249. list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"),
  250. G__getenv("LOCATION_NAME"), setname);
  251. for (i = 0; list[i]; i++) {
  252. fprintf(stdout, "%s\n", list[i]);
  253. }
  254. fflush(stdout);
  255. exit(EXIT_SUCCESS); /* leave r.proj after listing */
  256. }
  257. if (!inmap->answer)
  258. G_fatal_error(_("Required parameter <%s> not set"), inmap->key);
  259. if (!G_find_raster(inmap->answer, setname))
  260. G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"),
  261. inmap->answer, inlocation->answer, setname);
  262. /* Read input map colour table */
  263. have_colors = Rast_read_colors(inmap->answer, setname, &colr);
  264. /* Get projection info for input mapset */
  265. if ((in_proj_info = G_get_projinfo()) == NULL)
  266. G_fatal_error(_("Unable to get projection info of input map"));
  267. if ((in_unit_info = G_get_projunits()) == NULL)
  268. G_fatal_error(_("Unable to get projection units of input map"));
  269. if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0)
  270. G_fatal_error(_("Unable to get projection key values of input map"));
  271. G_free_key_value(in_proj_info);
  272. G_free_key_value(in_unit_info);
  273. G_free_key_value(out_proj_info);
  274. G_free_key_value(out_unit_info);
  275. if (G_verbose() > G_verbose_std())
  276. pj_print_proj_params(&iproj, &oproj);
  277. /* this call causes r.proj to read the entire map into memeory */
  278. Rast_get_cellhd(inmap->answer, setname, &incellhd);
  279. Rast_set_input_window(&incellhd);
  280. if (G_projection() == PROJECTION_XY)
  281. G_fatal_error(_("Unable to work with unprojected data (xy location)"));
  282. /* Save default borders so we can show them later */
  283. inorth = incellhd.north;
  284. isouth = incellhd.south;
  285. ieast = incellhd.east;
  286. iwest = incellhd.west;
  287. irows = incellhd.rows;
  288. icols = incellhd.cols;
  289. onorth = outcellhd.north;
  290. osouth = outcellhd.south;
  291. oeast = outcellhd.east;
  292. owest = outcellhd.west;
  293. orows = outcellhd.rows;
  294. ocols = outcellhd.cols;
  295. if (print_bounds->answer) {
  296. G_message(_("Input map <%s@%s> in location <%s>:"),
  297. inmap->answer, setname, inlocation->answer);
  298. if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0)
  299. G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));
  300. if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0)
  301. G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));
  302. G_format_northing(inorth, north_str, curr_proj);
  303. G_format_northing(isouth, south_str, curr_proj);
  304. G_format_easting(ieast, east_str, curr_proj);
  305. G_format_easting(iwest, west_str, curr_proj);
  306. if(gprint_bounds->answer) {
  307. fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n",
  308. north_str, south_str, west_str, east_str, irows, icols);
  309. }
  310. else {
  311. fprintf(stdout, "Source cols: %d\n", icols);
  312. fprintf(stdout, "Source rows: %d\n", irows);
  313. fprintf(stdout, "Local north: %s\n", north_str);
  314. fprintf(stdout, "Local south: %s\n", south_str);
  315. fprintf(stdout, "Local west: %s\n", west_str);
  316. fprintf(stdout, "Local east: %s\n", east_str);
  317. }
  318. /* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */
  319. exit(EXIT_SUCCESS);
  320. }
  321. /* Cut non-overlapping parts of input map */
  322. if (!nocrop->answer)
  323. bordwalk(&outcellhd, &incellhd, &oproj, &iproj);
  324. /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */
  325. /* (should probably be a factor based on input and output resolution) */
  326. incellhd.north += 2 * incellhd.ns_res;
  327. incellhd.east += 2 * incellhd.ew_res;
  328. incellhd.south -= 2 * incellhd.ns_res;
  329. incellhd.west -= 2 * incellhd.ew_res;
  330. if (incellhd.north > inorth)
  331. incellhd.north = inorth;
  332. if (incellhd.east > ieast)
  333. incellhd.east = ieast;
  334. if (incellhd.south < isouth)
  335. incellhd.south = isouth;
  336. if (incellhd.west < iwest)
  337. incellhd.west = iwest;
  338. Rast_set_input_window(&incellhd);
  339. /* And switch back to original location */
  340. G__switch_env();
  341. /* Adjust borders of output map */
  342. if (!nocrop->answer)
  343. bordwalk(&incellhd, &outcellhd, &iproj, &oproj);
  344. #if 0
  345. outcellhd.west = outcellhd.south = HUGE_VAL;
  346. outcellhd.east = outcellhd.north = -HUGE_VAL;
  347. for (row = 0; row < incellhd.rows; row++) {
  348. ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd);
  349. for (col = 0; col < incellhd.cols; col++) {
  350. xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd);
  351. pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj);
  352. if (xcoord1 > outcellhd.east)
  353. outcellhd.east = xcoord1;
  354. if (ycoord1 > outcellhd.north)
  355. outcellhd.north = ycoord1;
  356. if (xcoord1 < outcellhd.west)
  357. outcellhd.west = xcoord1;
  358. if (ycoord1 < outcellhd.south)
  359. outcellhd.south = ycoord1;
  360. }
  361. }
  362. #endif
  363. if (res->answer != NULL) /* set user defined resolution */
  364. outcellhd.ns_res = outcellhd.ew_res = atof(res->answer);
  365. G_adjust_Cell_head(&outcellhd, 0, 0);
  366. Rast_set_output_window(&outcellhd);
  367. G_message(" ");
  368. G_message(_("Input:"));
  369. G_message(_("Cols: %d (%d)"), incellhd.cols, icols);
  370. G_message(_("Rows: %d (%d)"), incellhd.rows, irows);
  371. G_message(_("North: %f (%f)"), incellhd.north, inorth);
  372. G_message(_("South: %f (%f)"), incellhd.south, isouth);
  373. G_message(_("West: %f (%f)"), incellhd.west, iwest);
  374. G_message(_("East: %f (%f)"), incellhd.east, ieast);
  375. G_message(_("EW-res: %f"), incellhd.ew_res);
  376. G_message(_("NS-res: %f"), incellhd.ns_res);
  377. G_message(" ");
  378. G_message(_("Output:"));
  379. G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols);
  380. G_message(_("Rows: %d (%d)"), outcellhd.rows, orows);
  381. G_message(_("North: %f (%f)"), outcellhd.north, onorth);
  382. G_message(_("South: %f (%f)"), outcellhd.south, osouth);
  383. G_message(_("West: %f (%f)"), outcellhd.west, owest);
  384. G_message(_("East: %f (%f)"), outcellhd.east, oeast);
  385. G_message(_("EW-res: %f"), outcellhd.ew_res);
  386. G_message(_("NS-res: %f"), outcellhd.ns_res);
  387. G_message(" ");
  388. /* open and read the relevant parts of the input map and close it */
  389. G__switch_env();
  390. Rast_set_input_window(&incellhd);
  391. fdi = Rast_open_old(inmap->answer, setname);
  392. cell_type = Rast_get_map_type(fdi);
  393. ibuffer = readcell(fdi, memory->answer);
  394. Rast_close(fdi);
  395. G__switch_env();
  396. Rast_set_output_window(&outcellhd);
  397. if (strcmp(interpol->answer, "nearest") == 0) {
  398. fdo = Rast_open_new(mapname, cell_type);
  399. obuffer = (CELL *) Rast_allocate_output_buf(cell_type);
  400. }
  401. else {
  402. fdo = Rast_open_fp_new(mapname);
  403. cell_type = FCELL_TYPE;
  404. obuffer = (FCELL *) Rast_allocate_output_buf(cell_type);
  405. }
  406. cell_size = Rast_cell_size(cell_type);
  407. xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
  408. /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2);
  409. /**/ G_important_message(_("Projecting..."));
  410. G_percent(0, outcellhd.rows, 2);
  411. for (row = 0; row < outcellhd.rows; row++) {
  412. obufptr = obuffer;
  413. for (col = 0; col < outcellhd.cols; col++) {
  414. /* project coordinates in output matrix to */
  415. /* coordinates in input matrix */
  416. if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0)
  417. Rast_set_null_value(obufptr, 1, cell_type);
  418. else {
  419. /* convert to row/column indices of input matrix */
  420. col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res;
  421. row_idx = (incellhd.north - ycoord1) / incellhd.ns_res;
  422. /* and resample data point */
  423. interpolate(ibuffer, obufptr, cell_type,
  424. &col_idx, &row_idx, &incellhd);
  425. }
  426. obufptr = G_incr_void_ptr(obufptr, cell_size);
  427. xcoord2 += outcellhd.ew_res;
  428. xcoord1 = xcoord2;
  429. ycoord1 = ycoord2;
  430. }
  431. Rast_put_row(fdo, obuffer, cell_type);
  432. xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
  433. ycoord2 -= outcellhd.ns_res;
  434. ycoord1 = ycoord2;
  435. G_percent(row, outcellhd.rows - 1, 2);
  436. }
  437. Rast_close(fdo);
  438. if (have_colors > 0) {
  439. Rast_write_colors(mapname, G_mapset(), &colr);
  440. Rast_free_colors(&colr);
  441. }
  442. Rast_short_history(mapname, "raster", &history);
  443. Rast_command_history(&history);
  444. Rast_write_history(mapname, &history);
  445. G_done_msg(NULL);
  446. exit(EXIT_SUCCESS);
  447. }
  448. char *make_ipol_list(void)
  449. {
  450. int size = 0;
  451. int i;
  452. char *buf;
  453. for (i = 0; menu[i].name; i++)
  454. size += strlen(menu[i].name) + 1;
  455. buf = G_malloc(size);
  456. *buf = '\0';
  457. for (i = 0; menu[i].name; i++) {
  458. if (i)
  459. strcat(buf, ",");
  460. strcat(buf, menu[i].name);
  461. }
  462. return buf;
  463. }
  464. char *make_ipol_desc(void)
  465. {
  466. int size = 0;
  467. int i;
  468. char *buf;
  469. for (i = 0; menu[i].name; i++)
  470. size += strlen(menu[i].name) + strlen(menu[i].text) + 2;
  471. buf = G_malloc(size);
  472. *buf = '\0';
  473. for (i = 0; menu[i].name; i++) {
  474. if (i)
  475. strcat(buf, ";");
  476. strcat(buf, menu[i].name);
  477. strcat(buf, ";");
  478. strcat(buf, menu[i].text);
  479. }
  480. return buf;
  481. }