r.import.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. #!/usr/bin/env python3
  2. ############################################################################
  3. #
  4. # MODULE: r.import
  5. #
  6. # AUTHOR(S): Markus Metz
  7. #
  8. # PURPOSE: Import and reproject on the fly
  9. #
  10. # COPYRIGHT: (C) 2015-2016 GRASS development team
  11. #
  12. # This program is free software under the GNU General
  13. # Public License (>=v2). Read the file COPYING that
  14. # comes with GRASS for details.
  15. #
  16. #############################################################################
  17. #%module
  18. #% description: Imports raster data into a GRASS raster map using GDAL library and reprojects on the fly.
  19. #% keyword: raster
  20. #% keyword: import
  21. #% keyword: projection
  22. #%end
  23. #%option G_OPT_F_BIN_INPUT
  24. #% description: Name of GDAL dataset to be imported
  25. #% guisection: Input
  26. #%end
  27. #%option
  28. #% key: band
  29. #% type: integer
  30. #% required: no
  31. #% multiple: yes
  32. #% description: Input band(s) to select (default is all bands)
  33. #% guisection: Input
  34. #%end
  35. #%option G_OPT_MEMORYMB
  36. #%end
  37. #%option G_OPT_R_OUTPUT
  38. #% description: Name for output raster map
  39. #% required: no
  40. #% guisection: Output
  41. #%end
  42. #%option
  43. #% key: resample
  44. #% type: string
  45. #% required: no
  46. #% multiple: no
  47. #% options: nearest,bilinear,bicubic,lanczos,bilinear_f,bicubic_f,lanczos_f
  48. #% description: Resampling method to use for reprojection
  49. #% descriptions: nearest;nearest neighbor;bilinear;bilinear interpolation;bicubic;bicubic interpolation;lanczos;lanczos filter;bilinear_f;bilinear interpolation with fallback;bicubic_f;bicubic interpolation with fallback;lanczos_f;lanczos filter with fallback
  50. #% answer: nearest
  51. #% guisection: Output
  52. #%end
  53. #%option
  54. #% key: extent
  55. #% type: string
  56. #% required: no
  57. #% multiple: no
  58. #% options: input,region
  59. #% answer: input
  60. #% description: Output raster map extent
  61. #% descriptions: region;extent of current region;input;extent of input map
  62. #% guisection: Output
  63. #%end
  64. #%option
  65. #% key: resolution
  66. #% type: string
  67. #% required: no
  68. #% multiple: no
  69. #% answer: estimated
  70. #% options: estimated,value,region
  71. #% description: Resolution of output raster map (default: estimated)
  72. #% descriptions: estimated;estimated resolution;value;user-specified resolution;region;current region resolution
  73. #% guisection: Output
  74. #%end
  75. #%option
  76. #% key: resolution_value
  77. #% type: double
  78. #% required: no
  79. #% multiple: no
  80. #% description: Resolution of output raster map (use with option resolution=value)
  81. #% guisection: Output
  82. #%end
  83. #%option
  84. #% key: title
  85. #% key_desc: phrase
  86. #% type: string
  87. #% required: no
  88. #% description: Title for resultant raster map
  89. #% guisection: Metadata
  90. #%end
  91. #%flag
  92. #% key: e
  93. #% description: Estimate resolution only
  94. #% guisection: Optional
  95. #%end
  96. #%flag
  97. #% key: n
  98. #% description: Do not perform region cropping optimization
  99. #% guisection: Optional
  100. #%end
  101. #%flag
  102. #% key: l
  103. #% description: Force Lat/Lon maps to fit into geographic coordinates (90N,S; 180E,W)
  104. #%end
  105. #%flag
  106. #% key: o
  107. #% label: Override projection check (use current location's projection)
  108. #% description: Assume that the dataset has the same projection as the current location
  109. #%end
  110. #%rules
  111. #% required: output,-e
  112. #%end
  113. import sys
  114. import os
  115. import atexit
  116. import math
  117. import grass.script as grass
  118. from grass.exceptions import CalledModuleError
  119. # initialize global vars
  120. TMPLOC = None
  121. SRCGISRC = None
  122. GISDBASE = None
  123. TMP_REG_NAME = None
  124. def cleanup():
  125. # remove temp location
  126. if TMPLOC:
  127. grass.try_rmdir(os.path.join(GISDBASE, TMPLOC))
  128. if SRCGISRC:
  129. grass.try_remove(SRCGISRC)
  130. if TMP_REG_NAME and grass.find_file(name=TMP_REG_NAME, element='vector',
  131. mapset=grass.gisenv()['MAPSET'])['fullname']:
  132. grass.run_command('g.remove', type='vector', name=TMP_REG_NAME,
  133. flags='f', quiet=True)
  134. def is_projection_matching(GDALdatasource):
  135. """Returns True if current location projection
  136. matches dataset projection, otherwise False"""
  137. try:
  138. grass.run_command('r.in.gdal', input=GDALdatasource, flags='j',
  139. quiet=True)
  140. return True
  141. except CalledModuleError:
  142. return False
  143. def main():
  144. global TMPLOC, SRCGISRC, GISDBASE, TMP_REG_NAME
  145. GDALdatasource = options['input']
  146. output = options['output']
  147. method = options['resample']
  148. memory = options['memory']
  149. bands = options['band']
  150. tgtres = options['resolution']
  151. title = options["title"]
  152. if flags['e'] and not output:
  153. output = 'rimport_tmp' # will be removed with the entire tmp location
  154. if options['resolution_value']:
  155. if tgtres != 'value':
  156. grass.fatal(_("To set custom resolution value, select 'value' in resolution option"))
  157. tgtres_value = float(options['resolution_value'])
  158. if tgtres_value <= 0:
  159. grass.fatal(_("Resolution value can't be smaller than 0"))
  160. elif tgtres == 'value':
  161. grass.fatal(
  162. _("Please provide the resolution for the imported dataset or change to 'estimated' resolution"))
  163. # try r.in.gdal directly first
  164. additional_flags = 'l' if flags['l'] else ''
  165. if flags['o']:
  166. additional_flags += 'o'
  167. region_flag = ''
  168. if options['extent'] == 'region':
  169. region_flag += 'r'
  170. if flags['o'] or is_projection_matching(GDALdatasource):
  171. parameters = dict(input=GDALdatasource, output=output,
  172. memory=memory, flags='ak' + additional_flags + region_flag)
  173. if bands:
  174. parameters['band'] = bands
  175. try:
  176. grass.run_command('r.in.gdal', **parameters)
  177. grass.verbose(
  178. _("Input <%s> successfully imported without reprojection") %
  179. GDALdatasource)
  180. return 0
  181. except CalledModuleError as e:
  182. grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)
  183. grassenv = grass.gisenv()
  184. tgtloc = grassenv['LOCATION_NAME']
  185. # make sure target is not xy
  186. if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
  187. grass.fatal(
  188. _("Coordinate reference system not available for current location <%s>") %
  189. tgtloc)
  190. tgtmapset = grassenv['MAPSET']
  191. GISDBASE = grassenv['GISDBASE']
  192. TMPLOC = 'temp_import_location_' + str(os.getpid())
  193. TMP_REG_NAME = 'vreg_tmp_' + str(os.getpid())
  194. SRCGISRC, src_env = grass.create_environment(GISDBASE, TMPLOC, 'PERMANENT')
  195. # create temp location from input without import
  196. grass.verbose(_("Creating temporary location for <%s>...") % GDALdatasource)
  197. # creating a new location with r.in.gdal requires a sanitized env
  198. env = os.environ.copy()
  199. env = grass.sanitize_mapset_environment(env)
  200. parameters = dict(input=GDALdatasource, output=output,
  201. memory=memory, flags='c', title=title,
  202. location=TMPLOC, quiet=True)
  203. if bands:
  204. parameters['band'] = bands
  205. try:
  206. grass.run_command('r.in.gdal', env=env, **parameters)
  207. except CalledModuleError:
  208. grass.fatal(_("Unable to read GDAL dataset <%s>") % GDALdatasource)
  209. # prepare to set region in temp location
  210. if 'r' in region_flag:
  211. tgtregion = TMP_REG_NAME
  212. grass.run_command('v.in.region', output=tgtregion, flags='d')
  213. # switch to temp location
  214. # print projection at verbose level
  215. grass.verbose(grass.read_command('g.proj', flags='p', env=src_env).rstrip(os.linesep))
  216. # make sure input is not xy
  217. if grass.parse_command('g.proj', flags='g', env=src_env)['name'] == 'xy_location_unprojected':
  218. grass.fatal(_("Coordinate reference system not available for input <%s>") % GDALdatasource)
  219. # import into temp location
  220. grass.verbose(_("Importing <%s> to temporary location...") % GDALdatasource)
  221. parameters = dict(input=GDALdatasource, output=output,
  222. memory=memory, flags='ak' + additional_flags)
  223. if bands:
  224. parameters['band'] = bands
  225. if 'r' in region_flag:
  226. grass.run_command('v.proj', location=tgtloc, mapset=tgtmapset,
  227. input=tgtregion, output=tgtregion, env=src_env)
  228. grass.run_command('g.region', vector=tgtregion, env=src_env)
  229. parameters['flags'] = parameters['flags'] + region_flag
  230. try:
  231. grass.run_command('r.in.gdal', env=src_env, **parameters)
  232. except CalledModuleError:
  233. grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)
  234. outfiles = grass.list_grouped('raster', env=src_env)['PERMANENT']
  235. # is output a group?
  236. group = False
  237. path = os.path.join(GISDBASE, TMPLOC, 'group', output)
  238. if os.path.exists(path):
  239. group = True
  240. path = os.path.join(GISDBASE, TMPLOC, 'group', output, 'POINTS')
  241. if os.path.exists(path):
  242. grass.fatal(_("Input contains GCPs, rectification is required"))
  243. if 'r' in region_flag:
  244. grass.run_command('g.remove', type="vector", flags="f",
  245. name=tgtregion, env=src_env)
  246. # switch to target location
  247. if 'r' in region_flag:
  248. grass.run_command('g.remove', type="vector", flags="f",
  249. name=tgtregion)
  250. region = grass.region()
  251. rflags = None
  252. if flags['n']:
  253. rflags = 'n'
  254. vreg = TMP_REG_NAME
  255. for outfile in outfiles:
  256. n = region['n']
  257. s = region['s']
  258. e = region['e']
  259. w = region['w']
  260. env = os.environ.copy()
  261. if options['extent'] == 'input':
  262. # r.proj -g
  263. try:
  264. tgtextents = grass.read_command('r.proj', location=TMPLOC,
  265. mapset='PERMANENT',
  266. input=outfile, flags='g',
  267. memory=memory, quiet=True)
  268. except CalledModuleError:
  269. grass.fatal(_("Unable to get reprojected map extent"))
  270. try:
  271. srcregion = grass.parse_key_val(tgtextents, val_type=float, vsep=' ')
  272. n = srcregion['n']
  273. s = srcregion['s']
  274. e = srcregion['e']
  275. w = srcregion['w']
  276. except ValueError: # import into latlong, expect 53:39:06.894826N
  277. srcregion = grass.parse_key_val(tgtextents, vsep=' ')
  278. n = grass.float_or_dms(srcregion['n'][:-1]) * \
  279. (-1 if srcregion['n'][-1] == 'S' else 1)
  280. s = grass.float_or_dms(srcregion['s'][:-1]) * \
  281. (-1 if srcregion['s'][-1] == 'S' else 1)
  282. e = grass.float_or_dms(srcregion['e'][:-1]) * \
  283. (-1 if srcregion['e'][-1] == 'W' else 1)
  284. w = grass.float_or_dms(srcregion['w'][:-1]) * \
  285. (-1 if srcregion['w'][-1] == 'W' else 1)
  286. env['GRASS_REGION'] = grass.region_env(n=n, s=s, e=e, w=w)
  287. # v.in.region in tgt
  288. grass.run_command('v.in.region', output=vreg, quiet=True, env=env)
  289. # reproject to src
  290. # switch to temp location
  291. try:
  292. grass.run_command('v.proj', input=vreg, output=vreg,
  293. location=tgtloc, mapset=tgtmapset,
  294. quiet=True, env=src_env)
  295. # test if v.proj created a valid area
  296. if grass.vector_info_topo(vreg, env=src_env)['areas'] != 1:
  297. grass.fatal(_("Please check the 'extent' parameter"))
  298. except CalledModuleError:
  299. grass.fatal(_("Unable to reproject to source location"))
  300. # set region from region vector
  301. grass.run_command('g.region', raster=outfile, env=src_env)
  302. grass.run_command('g.region', vector=vreg, env=src_env)
  303. # align to first band
  304. grass.run_command('g.region', align=outfile, env=src_env)
  305. # get number of cells
  306. cells = grass.region(env=src_env)['cells']
  307. estres = math.sqrt((n - s) * (e - w) / cells)
  308. # remove from source location for multi bands import
  309. grass.run_command('g.remove', type='vector', name=vreg,
  310. flags='f', quiet=True, env=src_env)
  311. # switch to target location
  312. grass.run_command('g.remove', type='vector', name=vreg,
  313. flags='f', quiet=True)
  314. grass.message(
  315. _("Estimated target resolution for input band <{out}>: {res}").format(
  316. out=outfile, res=estres))
  317. if flags['e']:
  318. continue
  319. env = os.environ.copy()
  320. if options['extent'] == 'input':
  321. env['GRASS_REGION'] = grass.region_env(n=n, s=s, e=e, w=w)
  322. res = None
  323. if tgtres == 'estimated':
  324. res = estres
  325. elif tgtres == 'value':
  326. res = tgtres_value
  327. grass.message(
  328. _("Using given resolution for input band <{out}>: {res}").format(
  329. out=outfile, res=res))
  330. # align to requested resolution
  331. env['GRASS_REGION'] = grass.region_env(res=res, flags='a', env=env)
  332. else:
  333. curr_reg = grass.region()
  334. grass.message(_("Using current region resolution for input band "
  335. "<{out}>: nsres={ns}, ewres={ew}").format(out=outfile, ns=curr_reg['nsres'],
  336. ew=curr_reg['ewres']))
  337. # r.proj
  338. grass.message(_("Reprojecting <%s>...") % outfile)
  339. try:
  340. grass.run_command('r.proj', location=TMPLOC,
  341. mapset='PERMANENT', input=outfile,
  342. method=method, resolution=res,
  343. memory=memory, flags=rflags, quiet=True,
  344. env=env)
  345. except CalledModuleError:
  346. grass.fatal(_("Unable to to reproject raster <%s>") % outfile)
  347. if grass.raster_info(outfile)['min'] is None:
  348. grass.fatal(_("The reprojected raster <%s> is empty") % outfile)
  349. if flags['e']:
  350. return 0
  351. if group:
  352. grass.run_command('i.group', group=output, input=','.join(outfiles))
  353. # TODO: write metadata with r.support
  354. return 0
  355. if __name__ == "__main__":
  356. options, flags = grass.parser()
  357. atexit.register(cleanup)
  358. sys.exit(main())