r.import.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. if flags['o'] or grass.run_command('r.in.gdal', input=GDALdatasource, flags='j',
  199. errors='status', quiet=True) == 0:
  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. grass.verbose(
  207. _("Input <%s> successfully imported without reprojection") %
  208. GDALdatasource)
  209. return 0
  210. except CalledModuleError as e:
  211. grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)
  212. # make sure target is not xy
  213. if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
  214. grass.fatal(
  215. _("Coordinate reference system not available for current location <%s>") %
  216. tgtloc)
  217. # switch to temp location
  218. os.environ['GISRC'] = str(SRCGISRC)
  219. # make sure input is not xy
  220. if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
  221. grass.fatal(_("Coordinate reference system not available for input <%s>") % GDALdatasource)
  222. # import into temp location
  223. grass.verbose(_("Importing <%s> to temporary location...") % GDALdatasource)
  224. parameters = dict(input=GDALdatasource, output=output,
  225. memory=memory, flags='k' + additional_flags)
  226. if bands:
  227. parameters['band'] = bands
  228. try:
  229. grass.run_command('r.in.gdal', **parameters)
  230. except CalledModuleError:
  231. grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)
  232. outfiles = grass.list_grouped('raster')['PERMANENT']
  233. # is output a group?
  234. group = False
  235. path = os.path.join(GISDBASE, TMPLOC, 'group', output)
  236. if os.path.exists(path):
  237. group = True
  238. path = os.path.join(GISDBASE, TMPLOC, 'group', output, 'POINTS')
  239. if os.path.exists(path):
  240. grass.fatal(_("Input contains GCPs, rectification is required"))
  241. # switch to target location
  242. os.environ['GISRC'] = str(tgtgisrc)
  243. region = grass.region()
  244. rflags = None
  245. if flags['n']:
  246. rflags = 'n'
  247. for outfile in outfiles:
  248. n = region['n']
  249. s = region['s']
  250. e = region['e']
  251. w = region['w']
  252. grass.use_temp_region()
  253. if options['extent'] == 'input':
  254. # r.proj -g
  255. try:
  256. tgtextents = grass.read_command('r.proj', location=TMPLOC,
  257. mapset='PERMANENT',
  258. input=outfile, flags='g',
  259. memory=memory, quiet=True)
  260. except CalledModuleError:
  261. grass.fatal(_("Unable to get reprojected map extent"))
  262. try:
  263. srcregion = grass.parse_key_val(tgtextents, val_type=float, vsep=' ')
  264. n = srcregion['n']
  265. s = srcregion['s']
  266. e = srcregion['e']
  267. w = srcregion['w']
  268. except ValueError: # import into latlong, expect 53:39:06.894826N
  269. srcregion = grass.parse_key_val(tgtextents, vsep=' ')
  270. n = grass.float_or_dms(srcregion['n'][:-1]) * \
  271. (-1 if srcregion['n'][-1] == 'S' else 1)
  272. s = grass.float_or_dms(srcregion['s'][:-1]) * \
  273. (-1 if srcregion['s'][-1] == 'S' else 1)
  274. e = grass.float_or_dms(srcregion['e'][:-1]) * \
  275. (-1 if srcregion['e'][-1] == 'W' else 1)
  276. w = grass.float_or_dms(srcregion['w'][:-1]) * \
  277. (-1 if srcregion['w'][-1] == 'W' else 1)
  278. grass.run_command('g.region', n=n, s=s, e=e, w=w)
  279. # v.in.region in tgt
  280. vreg = TMP_REG_NAME = 'vreg_tmp_' + str(os.getpid())
  281. grass.run_command('v.in.region', output=vreg, quiet=True)
  282. grass.del_temp_region()
  283. # reproject to src
  284. # switch to temp location
  285. os.environ['GISRC'] = str(SRCGISRC)
  286. try:
  287. grass.run_command('v.proj', input=vreg, output=vreg,
  288. location=tgtloc, mapset=tgtmapset, quiet=True)
  289. except CalledModuleError:
  290. grass.fatal(_("Unable to reproject to source location"))
  291. # set region from region vector
  292. grass.run_command('g.region', raster=outfile)
  293. grass.run_command('g.region', vector=vreg)
  294. # align to first band
  295. grass.run_command('g.region', align=outfile)
  296. # get number of cells
  297. cells = grass.region()['cells']
  298. estres = math.sqrt((n - s) * (e - w) / cells)
  299. # remove from source location for multi bands import
  300. grass.run_command('g.remove', type='vector', name=vreg,
  301. flags='f', quiet=True)
  302. os.environ['GISRC'] = str(tgtgisrc)
  303. grass.run_command('g.remove', type='vector', name=vreg,
  304. flags='f', quiet=True)
  305. grass.message(
  306. _("Estimated target resolution for input band <{out}>: {res}").format(
  307. out=outfile, res=estres))
  308. if flags['e']:
  309. continue
  310. if options['extent'] == 'input':
  311. grass.use_temp_region()
  312. grass.run_command('g.region', n=n, s=s, e=e, w=w)
  313. res = None
  314. if tgtres == 'estimated':
  315. res = estres
  316. elif tgtres == 'value':
  317. res = tgtres_value
  318. grass.message(
  319. _("Using given resolution for input band <{out}>: {res}").format(
  320. out=outfile, res=res))
  321. # align to requested resolution
  322. grass.run_command('g.region', res=res, flags='a')
  323. else:
  324. curr_reg = grass.region()
  325. grass.message(_("Using current region resolution for input band "
  326. "<{out}>: nsres={ns}, ewres={ew}").format(out=outfile, ns=curr_reg['nsres'],
  327. ew=curr_reg['ewres']))
  328. # r.proj
  329. grass.message(_("Reprojecting <%s>...") % outfile)
  330. try:
  331. grass.run_command('r.proj', location=TMPLOC,
  332. mapset='PERMANENT', input=outfile,
  333. method=method, resolution=res,
  334. memory=memory, flags=rflags, quiet=True)
  335. except CalledModuleError:
  336. grass.fatal(_("Unable to to reproject raster <%s>") % outfile)
  337. if grass.raster_info(outfile)['min'] is None:
  338. grass.fatal(_("The reprojected raster <%s> is empty") % outfile)
  339. if options['extent'] == 'input':
  340. grass.del_temp_region()
  341. if flags['e']:
  342. return 0
  343. if group:
  344. grass.run_command('i.group', group=output, input=','.join(outfiles))
  345. # TODO: write metadata with r.support
  346. return 0
  347. if __name__ == "__main__":
  348. options, flags = grass.parser()
  349. atexit.register(cleanup)
  350. sys.exit(main())