r.import.py 12 KB

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