main.c 18 KB

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