r.import.py 13 KB

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