r.import.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. # initialize global vars
  128. TMPLOC = None
  129. SRCGISRC = None
  130. GISDBASE = None
  131. TMP_REG_NAME = None
  132. def cleanup():
  133. # remove temp location
  134. if TMPLOC:
  135. grass.try_rmdir(os.path.join(GISDBASE, TMPLOC))
  136. if SRCGISRC:
  137. grass.try_remove(SRCGISRC)
  138. if TMP_REG_NAME and grass.find_file(name=TMP_REG_NAME, element='vector',
  139. mapset=grass.gisenv()['MAPSET'])['fullname']:
  140. grass.run_command('g.remove', type='vector', name=TMP_REG_NAME,
  141. flags='f', quiet=True)
  142. def main():
  143. global TMPLOC, SRCGISRC, GISDBASE, TMP_REG_NAME
  144. GDALdatasource = options['input']
  145. output = options['output']
  146. method = options['resample']
  147. memory = options['memory']
  148. bands = options['band']
  149. tgtres = options['resolution']
  150. title = options["title"]
  151. if flags['e'] and not output:
  152. output = 'rimport_tmp' # will be removed with the entire tmp location
  153. if options['resolution_value']:
  154. if tgtres != 'value':
  155. grass.fatal(_("To set custom resolution value, select 'value' in resolution option"))
  156. tgtres_value = float(options['resolution_value'])
  157. if tgtres_value <= 0:
  158. grass.fatal(_("Resolution value can't be smaller than 0"))
  159. elif tgtres == 'value':
  160. grass.fatal(
  161. _("Please provide the resolution for the imported dataset or change to 'estimated' resolution"))
  162. grassenv = grass.gisenv()
  163. tgtloc = grassenv['LOCATION_NAME']
  164. tgtmapset = grassenv['MAPSET']
  165. GISDBASE = grassenv['GISDBASE']
  166. tgtgisrc = os.environ['GISRC']
  167. SRCGISRC = grass.tempfile()
  168. TMPLOC = 'temp_import_location_' + str(os.getpid())
  169. f = open(SRCGISRC, 'w')
  170. f.write('MAPSET: PERMANENT\n')
  171. f.write('GISDBASE: %s\n' % GISDBASE)
  172. f.write('LOCATION_NAME: %s\n' % TMPLOC)
  173. f.write('GUI: text\n')
  174. f.close()
  175. tgtsrs = grass.read_command('g.proj', flags='j', quiet=True)
  176. # create temp location from input without import
  177. grass.verbose(_("Creating temporary location for <%s>...") % GDALdatasource)
  178. parameters = dict(input=GDALdatasource, output=output,
  179. memory=memory, flags='c', title=title,
  180. location=TMPLOC, quiet=True)
  181. if bands:
  182. parameters['band'] = bands
  183. try:
  184. grass.run_command('r.in.gdal', **parameters)
  185. except CalledModuleError:
  186. grass.fatal(_("Unable to read GDAL dataset <%s>") % GDALdatasource)
  187. # switch to temp location
  188. os.environ['GISRC'] = str(SRCGISRC)
  189. # switch to target location
  190. os.environ['GISRC'] = str(tgtgisrc)
  191. # try r.in.gdal directly first
  192. additional_flags = 'l' if flags['l'] else ''
  193. if flags['o']:
  194. additional_flags += 'o'
  195. if flags['o'] or grass.run_command('r.in.gdal', input=GDALdatasource, flags='j',
  196. errors='status', quiet=True) == 0:
  197. parameters = dict(input=GDALdatasource, output=output,
  198. memory=memory, flags='k' + additional_flags)
  199. if bands:
  200. parameters['band'] = bands
  201. try:
  202. grass.run_command('r.in.gdal', **parameters)
  203. grass.verbose(
  204. _("Input <%s> successfully imported without reprojection") %
  205. GDALdatasource)
  206. return 0
  207. except CalledModuleError as e:
  208. grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)
  209. # make sure target is not xy
  210. if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
  211. grass.fatal(
  212. _("Coordinate reference system not available for current location <%s>") %
  213. tgtloc)
  214. # switch to temp location
  215. os.environ['GISRC'] = str(SRCGISRC)
  216. # make sure input is not xy
  217. if grass.parse_command('g.proj', flags='g')['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='k' + additional_flags)
  223. if bands:
  224. parameters['band'] = bands
  225. try:
  226. grass.run_command('r.in.gdal', **parameters)
  227. except CalledModuleError:
  228. grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)
  229. outfiles = grass.list_grouped('raster')['PERMANENT']
  230. # is output a group?
  231. group = False
  232. path = os.path.join(GISDBASE, TMPLOC, 'group', output)
  233. if os.path.exists(path):
  234. group = True
  235. path = os.path.join(GISDBASE, TMPLOC, 'group', output, 'POINTS')
  236. if os.path.exists(path):
  237. grass.fatal(_("Input contains GCPs, rectification is required"))
  238. # switch to target location
  239. os.environ['GISRC'] = str(tgtgisrc)
  240. region = grass.region()
  241. rflags = None
  242. if flags['n']:
  243. rflags = 'n'
  244. for outfile in outfiles:
  245. n = region['n']
  246. s = region['s']
  247. e = region['e']
  248. w = region['w']
  249. grass.use_temp_region()
  250. if options['extent'] == 'input':
  251. # r.proj -g
  252. try:
  253. tgtextents = grass.read_command('r.proj', location=TMPLOC,
  254. mapset='PERMANENT',
  255. input=outfile, flags='g',
  256. memory=memory, quiet=True)
  257. except CalledModuleError:
  258. grass.fatal(_("Unable to get reprojected map extent"))
  259. try:
  260. srcregion = grass.parse_key_val(tgtextents, val_type=float, vsep=' ')
  261. n = srcregion['n']
  262. s = srcregion['s']
  263. e = srcregion['e']
  264. w = srcregion['w']
  265. except ValueError: # import into latlong, expect 53:39:06.894826N
  266. srcregion = grass.parse_key_val(tgtextents, vsep=' ')
  267. n = grass.float_or_dms(srcregion['n'][:-1]) * \
  268. (-1 if srcregion['n'][-1] == 'S' else 1)
  269. s = grass.float_or_dms(srcregion['s'][:-1]) * \
  270. (-1 if srcregion['s'][-1] == 'S' else 1)
  271. e = grass.float_or_dms(srcregion['e'][:-1]) * \
  272. (-1 if srcregion['e'][-1] == 'W' else 1)
  273. w = grass.float_or_dms(srcregion['w'][:-1]) * \
  274. (-1 if srcregion['w'][-1] == 'W' else 1)
  275. grass.run_command('g.region', n=n, s=s, e=e, w=w)
  276. # v.in.region in tgt
  277. vreg = TMP_REG_NAME = 'vreg_tmp_' + str(os.getpid())
  278. grass.run_command('v.in.region', output=vreg, quiet=True)
  279. grass.del_temp_region()
  280. # reproject to src
  281. # switch to temp location
  282. os.environ['GISRC'] = str(SRCGISRC)
  283. try:
  284. grass.run_command('v.proj', input=vreg, output=vreg,
  285. location=tgtloc, mapset=tgtmapset, quiet=True)
  286. except CalledModuleError:
  287. grass.fatal(_("Unable to reproject to source location"))
  288. # set region from region vector
  289. grass.run_command('g.region', raster=outfile)
  290. grass.run_command('g.region', vector=vreg)
  291. # align to first band
  292. grass.run_command('g.region', align=outfile)
  293. # get number of cells
  294. cells = grass.region()['cells']
  295. estres = math.sqrt((n - s) * (e - w) / cells)
  296. # remove from source location for multi bands import
  297. grass.run_command('g.remove', type='vector', name=vreg,
  298. flags='f', quiet=True)
  299. os.environ['GISRC'] = str(tgtgisrc)
  300. grass.run_command('g.remove', type='vector', name=vreg,
  301. flags='f', quiet=True)
  302. grass.message(
  303. _("Estimated target resolution for input band <{out}>: {res}").format(
  304. out=outfile, res=estres))
  305. if flags['e']:
  306. continue
  307. if options['extent'] == 'input':
  308. grass.use_temp_region()
  309. grass.run_command('g.region', n=n, s=s, e=e, w=w)
  310. res = None
  311. if tgtres == 'estimated':
  312. res = estres
  313. elif tgtres == 'value':
  314. res = tgtres_value
  315. grass.message(
  316. _("Using given resolution for input band <{out}>: {res}").format(
  317. out=outfile, res=res))
  318. # align to requested resolution
  319. grass.run_command('g.region', res=res, flags='a')
  320. else:
  321. curr_reg = grass.region()
  322. grass.message(_("Using current region resolution for input band "
  323. "<{out}>: nsres={ns}, ewres={ew}").format(out=outfile, ns=curr_reg['nsres'],
  324. ew=curr_reg['ewres']))
  325. # r.proj
  326. grass.message(_("Reprojecting <%s>...") % outfile)
  327. try:
  328. grass.run_command('r.proj', location=TMPLOC,
  329. mapset='PERMANENT', input=outfile,
  330. method=method, resolution=res,
  331. memory=memory, flags=rflags, quiet=True)
  332. except CalledModuleError:
  333. grass.fatal(_("Unable to to reproject raster <%s>") % outfile)
  334. if grass.raster_info(outfile)['min'] is None:
  335. grass.fatal(_("The reprojected raster <%s> is empty") % outfile)
  336. if options['extent'] == 'input':
  337. grass.del_temp_region()
  338. if flags['e']:
  339. return 0
  340. if group:
  341. grass.run_command('i.group', group=output, input=','.join(outfiles))
  342. # TODO: write metadata with r.support
  343. return 0
  344. if __name__ == "__main__":
  345. options, flags = grass.parser()
  346. atexit.register(cleanup)
  347. sys.exit(main())