r.import.py 14 KB

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