r.import.py 13 KB

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