r.fillnulls.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. #!/usr/bin/env python
  2. #
  3. ############################################################################
  4. #
  5. # MODULE: r.fillnulls
  6. # AUTHOR(S): Markus Neteler
  7. # Updated to GRASS 5.7 by Michael Barton
  8. # Updated to GRASS 6.0 by Markus Neteler
  9. # Ring and zoom improvements by Hamish Bowman
  10. # Converted to Python by Glynn Clements
  11. # Added support for r.resamp.bspline by Luca Delucchi
  12. # Per hole filling with RST by Maris Nartiss
  13. # Speedup for per hole filling with RST by Stefan Blumentrath
  14. # PURPOSE: fills NULL (no data areas) in raster maps
  15. # The script respects a user mask (MASK) if present.
  16. #
  17. # COPYRIGHT: (C) 2001-2014 by the GRASS Development Team
  18. #
  19. # This program is free software under the GNU General Public
  20. # License (>=v2). Read the file COPYING that comes with GRASS
  21. # for details.
  22. #
  23. #############################################################################
  24. #%module
  25. #% description: Fills no-data areas in raster maps using spline interpolation.
  26. #% keyword: raster
  27. #% keyword: elevation
  28. #% keyword: interpolation
  29. #%end
  30. #%option G_OPT_R_INPUT
  31. #%end
  32. #%option G_OPT_R_OUTPUT
  33. #%end
  34. #%option
  35. #% key: method
  36. #% type: string
  37. #% description: Interpolation method to use
  38. #% required: yes
  39. #% options: bilinear,bicubic,rst
  40. #% answer: rst
  41. #%end
  42. #%option
  43. #% key: tension
  44. #% type: double
  45. #% description: Spline tension parameter
  46. #% required : no
  47. #% answer : 40.
  48. #% guisection: RST options
  49. #%end
  50. #%option
  51. #% key: smooth
  52. #% type: double
  53. #% description: Spline smoothing parameter
  54. #% required : no
  55. #% answer : 0.1
  56. #% guisection: RST options
  57. #%end
  58. #%option
  59. #% key: edge
  60. #% type: integer
  61. #% description: Width of hole edge used for interpolation (in cells)
  62. #% required : no
  63. #% answer : 3
  64. #% options : 2-100
  65. #% guisection: RST options
  66. #%end
  67. #%option
  68. #% key: npmin
  69. #% type: integer
  70. #% description: Minimum number of points for approximation in a segment (>segmax)
  71. #% required : no
  72. #% answer : 600
  73. #% options : 2-10000
  74. #% guisection: RST options
  75. #%end
  76. #%option
  77. #% key: segmax
  78. #% type: integer
  79. #% description: Maximum number of points in a segment
  80. #% required : no
  81. #% answer : 300
  82. #% options : 2-10000
  83. #% guisection: RST options
  84. #%end
  85. import sys
  86. import os
  87. import atexit
  88. import grass.script as grass
  89. from grass.exceptions import CalledModuleError
  90. tmp_rmaps = list()
  91. tmp_vmaps = list()
  92. usermask = None
  93. mapset = None
  94. # what to do in case of user break:
  95. def cleanup():
  96. # delete internal mask and any TMP files:
  97. if len(tmp_vmaps) > 0:
  98. grass.run_command('g.remove', quiet=True, flags='fb', type='vector', name=tmp_vmaps)
  99. if len(tmp_rmaps) > 0:
  100. grass.run_command('g.remove', quiet=True, flags='fb', type='raster', name=tmp_rmaps)
  101. if usermask and mapset:
  102. if grass.find_file(usermask, mapset=mapset)['file']:
  103. grass.run_command('g.rename', quiet=True, raster=(usermask, 'MASK'), overwrite=True)
  104. def main():
  105. global usermask, mapset, tmp_rmaps, tmp_vmaps
  106. input = options['input']
  107. output = options['output']
  108. tension = options['tension']
  109. smooth = options['smooth']
  110. method = options['method']
  111. edge = int(options['edge'])
  112. segmax = int(options['segmax'])
  113. npmin = int(options['npmin'])
  114. quiet = True # FIXME
  115. mapset = grass.gisenv()['MAPSET']
  116. unique = str(os.getpid()) # Shouldn't we use temp name?
  117. prefix = 'r_fillnulls_%s_' % unique
  118. failed_list = list() # a list of failed holes. Caused by issues with v.surf.rst. Connected with #1813
  119. # check if input file exists
  120. if not grass.find_file(input)['file']:
  121. grass.fatal(_("Raster map <%s> not found") % input)
  122. # save original region
  123. reg_org = grass.region()
  124. # check if a MASK is already present
  125. # and remove it to not interfere with NULL lookup part
  126. # as we don't fill MASKed parts!
  127. if grass.find_file('MASK', mapset=mapset)['file']:
  128. usermask = "usermask_mask." + unique
  129. grass.message(_("A user raster mask (MASK) is present. Saving it..."))
  130. grass.run_command('g.rename', quiet=quiet, raster=('MASK', usermask))
  131. # check if method is rst to use v.surf.rst
  132. if method == 'rst':
  133. # idea: filter all NULLS and grow that area(s) by 3 pixel, then
  134. # interpolate from these surrounding 3 pixel edge
  135. filling = prefix + 'filled'
  136. grass.use_temp_region()
  137. grass.run_command('g.region', align=input, quiet=quiet)
  138. region = grass.region()
  139. ns_res = region['nsres']
  140. ew_res = region['ewres']
  141. grass.message(_("Using RST interpolation..."))
  142. grass.message(_("Locating and isolating NULL areas..."))
  143. # creating binary (0/1) map
  144. if usermask:
  145. grass.message(_("Skipping masked raster parts"))
  146. grass.mapcalc("$tmp1 = if(isnull($input) && !($mask == 0 || isnull($mask)),1,null())",
  147. tmp1=prefix + 'nulls', input=input, mask=usermask)
  148. else:
  149. grass.mapcalc("$tmp1 = if(isnull($input),1,null())",
  150. tmp1=prefix + 'nulls', input=input)
  151. tmp_rmaps.append(prefix + 'nulls')
  152. # restoring user's mask, if present
  153. # to ignore MASKed original values
  154. if usermask:
  155. grass.message(_("Restoring user mask (MASK)..."))
  156. try:
  157. grass.run_command('g.rename', quiet=quiet, raster=(usermask, 'MASK'))
  158. except CalledModuleError:
  159. grass.warning(_("Failed to restore user MASK!"))
  160. usermask = None
  161. # grow identified holes by X pixels
  162. grass.message(_("Growing NULL areas"))
  163. tmp_rmaps.append(prefix + 'grown')
  164. try:
  165. grass.run_command('r.grow', input=prefix + 'nulls',
  166. radius=edge + 0.01, old=1, new=1,
  167. out=prefix + 'grown', quiet=quiet)
  168. except CalledModuleError:
  169. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  170. # assign unique IDs to each hole or hole system (holes closer than edge distance)
  171. grass.message(_("Assigning IDs to NULL areas"))
  172. tmp_rmaps.append(prefix + 'clumped')
  173. try:
  174. grass.run_command(
  175. 'r.clump',
  176. input=prefix +
  177. 'grown',
  178. output=prefix +
  179. 'clumped',
  180. quiet=quiet)
  181. except CalledModuleError:
  182. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  183. # get a list of unique hole cat's
  184. grass.mapcalc("$out = if(isnull($inp), null(), $clumped)",
  185. out=prefix + 'holes', inp=prefix + 'nulls', clumped=prefix + 'clumped')
  186. tmp_rmaps.append(prefix + 'holes')
  187. # use new IDs to identify holes
  188. try:
  189. grass.run_command('r.to.vect', flags='v',
  190. input=prefix + 'holes', output=prefix + 'holes',
  191. type='area', quiet=quiet)
  192. except:
  193. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  194. tmp_vmaps.append(prefix + 'holes')
  195. # get a list of unique hole cat's
  196. cats_file_name = grass.tempfile(False)
  197. grass.run_command(
  198. 'v.db.select',
  199. flags='c',
  200. map=prefix + 'holes',
  201. columns='cat',
  202. file=cats_file_name,
  203. quiet=quiet)
  204. cat_list = list()
  205. cats_file = file(cats_file_name)
  206. for line in cats_file:
  207. cat_list.append(line.rstrip('\n'))
  208. cats_file.close()
  209. os.remove(cats_file_name)
  210. if len(cat_list) < 1:
  211. grass.fatal(_("Input map has no holes. Check region settings."))
  212. # GTC Hole is NULL area in a raster map
  213. grass.message(_("Processing %d map holes") % len(cat_list))
  214. first = True
  215. hole_n = 1
  216. for cat in cat_list:
  217. holename = prefix + 'hole_' + cat
  218. # GTC Hole is a NULL area in a raster map
  219. grass.message(_("Filling hole %s of %s") % (hole_n, len(cat_list)))
  220. hole_n = hole_n + 1
  221. # cut out only CAT hole for processing
  222. try:
  223. grass.run_command('v.extract', input=prefix + 'holes',
  224. output=holename + '_pol',
  225. cats=cat, quiet=quiet)
  226. except CalledModuleError:
  227. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  228. tmp_vmaps.append(holename + '_pol')
  229. # zoom to specific hole with a buffer of two cells around the hole to
  230. # remove rest of data
  231. try:
  232. grass.run_command('g.region',
  233. vector=holename + '_pol', align=input,
  234. w='w-%d' % (edge * 2 * ew_res),
  235. e='e+%d' % (edge * 2 * ew_res),
  236. n='n+%d' % (edge * 2 * ns_res),
  237. s='s-%d' % (edge * 2 * ns_res),
  238. quiet=quiet)
  239. except CalledModuleError:
  240. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  241. # remove temporary map to not overfill disk
  242. try:
  243. grass.run_command('g.remove', flags='fb', type='vector',
  244. name=holename + '_pol', quiet=quiet)
  245. except CalledModuleError:
  246. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  247. tmp_vmaps.remove(holename + '_pol')
  248. # copy only data around hole
  249. grass.mapcalc("$out = if($inp == $catn, $inp, null())",
  250. out=holename, inp=prefix + 'holes', catn=cat)
  251. tmp_rmaps.append(holename)
  252. # If here loop is split into two, next part of loop can be run in parallel
  253. # (except final result patching)
  254. # Downside - on large maps such approach causes large disk usage
  255. # grow hole border to get it's edge area
  256. tmp_rmaps.append(holename + '_grown')
  257. try:
  258. grass.run_command('r.grow', input=holename, radius=edge + 0.01,
  259. old=-1, out=holename + '_grown', quiet=quiet)
  260. except CalledModuleError:
  261. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  262. # no idea why r.grow old=-1 doesn't replace existing values with NULL
  263. grass.mapcalc("$out = if($inp == -1, null(), $dem)",
  264. out=holename + '_edges', inp=holename + '_grown', dem=input)
  265. tmp_rmaps.append(holename + '_edges')
  266. # convert to points for interpolation
  267. tmp_vmaps.append(holename)
  268. try:
  269. grass.run_command('r.to.vect',
  270. input=holename + '_edges', output=holename,
  271. type='point', flags='z', quiet=quiet)
  272. except CalledModuleError:
  273. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  274. # count number of points to control segmax parameter for interpolation:
  275. pointsnumber = grass.vector_info_topo(map=holename)['points']
  276. grass.verbose(_("Interpolating %d points") % pointsnumber)
  277. if pointsnumber < 2:
  278. grass.verbose(_("No points to interpolate"))
  279. failed_list.append(holename)
  280. continue
  281. # Avoid v.surf.rst warnings
  282. if pointsnumber < segmax:
  283. npmin = pointsnumber + 1
  284. segmax = pointsnumber
  285. # launch v.surf.rst
  286. tmp_rmaps.append(holename + '_dem')
  287. try:
  288. grass.run_command('v.surf.rst', quiet=quiet,
  289. input=holename, elev=holename + '_dem',
  290. tension=tension, smooth=smooth,
  291. segmax=segmax, npmin=npmin)
  292. except CalledModuleError:
  293. # GTC Hole is NULL area in a raster map
  294. grass.fatal(_("Failed to fill hole %s") % cat)
  295. # v.surf.rst sometimes fails with exit code 0
  296. # related bug #1813
  297. if not grass.find_file(holename + '_dem')['file']:
  298. try:
  299. tmp_rmaps.remove(holename)
  300. tmp_rmaps.remove(holename + '_grown')
  301. tmp_rmaps.remove(holename + '_edges')
  302. tmp_rmaps.remove(holename + '_dem')
  303. tmp_vmaps.remove(holename)
  304. except:
  305. pass
  306. grass.warning(
  307. _("Filling has failed silently. Leaving temporary maps with prefix <%s> for debugging.") %
  308. holename)
  309. failed_list.append(holename)
  310. continue
  311. # append hole result to interpolated version later used to patch into original DEM
  312. if first:
  313. tmp_rmaps.append(filling)
  314. grass.run_command('g.region', align=input, raster=holename + '_dem', quiet=quiet)
  315. grass.mapcalc("$out = if(isnull($inp), null(), $dem)",
  316. out=filling, inp=holename, dem=holename + '_dem')
  317. first = False
  318. else:
  319. tmp_rmaps.append(filling + '_tmp')
  320. grass.run_command(
  321. 'g.region', align=input, raster=(
  322. filling, holename + '_dem'), quiet=quiet)
  323. grass.mapcalc(
  324. "$out = if(isnull($inp), if(isnull($fill), null(), $fill), $dem)",
  325. out=filling + '_tmp',
  326. inp=holename,
  327. dem=holename + '_dem',
  328. fill=filling)
  329. try:
  330. grass.run_command('g.rename',
  331. raster=(filling + '_tmp', filling),
  332. overwrite=True, quiet=quiet)
  333. except CalledModuleError:
  334. grass.fatal(
  335. _("abandoned. Removing temporary maps, restoring user mask if needed:"))
  336. # this map has been removed. No need for later cleanup.
  337. tmp_rmaps.remove(filling + '_tmp')
  338. # remove temporary maps to not overfill disk
  339. try:
  340. tmp_rmaps.remove(holename)
  341. tmp_rmaps.remove(holename + '_grown')
  342. tmp_rmaps.remove(holename + '_edges')
  343. tmp_rmaps.remove(holename + '_dem')
  344. except:
  345. pass
  346. try:
  347. grass.run_command('g.remove', quiet=quiet,
  348. flags='fb', type='raster',
  349. name=(holename,
  350. holename + '_grown',
  351. holename + '_edges',
  352. holename + '_dem'))
  353. except CalledModuleError:
  354. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  355. try:
  356. tmp_vmaps.remove(holename)
  357. except:
  358. pass
  359. try:
  360. grass.run_command('g.remove', quiet=quiet, flags='fb',
  361. type='vector', name=holename)
  362. except CalledModuleError:
  363. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  364. # check if method is different from rst to use r.resamp.bspline
  365. if method != 'rst':
  366. grass.message(_("Using %s bspline interpolation") % method)
  367. # clone current region
  368. grass.use_temp_region()
  369. grass.run_command('g.region', align=input)
  370. reg = grass.region()
  371. # launch r.resamp.bspline
  372. tmp_rmaps.append(prefix + 'filled')
  373. if usermask:
  374. grass.run_command('r.resamp.bspline', input=input, mask=usermask,
  375. output=prefix + 'filled', method=method,
  376. ew_step=3 * reg['ewres'], ns_step=3 * reg['nsres'],
  377. lambda_=0.01, flags='n')
  378. else:
  379. grass.run_command('r.resamp.bspline', input=input,
  380. output=prefix + 'filled', method=method,
  381. ew_step=3 * reg['ewres'], ns_step=3 * reg['nsres'],
  382. lambda_=0.01, flags='n')
  383. # restoring user's mask, if present:
  384. if usermask:
  385. grass.message(_("Restoring user mask (MASK)..."))
  386. try:
  387. grass.run_command('g.rename', quiet=quiet, raster=(usermask, 'MASK'))
  388. except CalledModuleError:
  389. grass.warning(_("Failed to restore user MASK!"))
  390. usermask = None
  391. # set region to original extents, align to input
  392. grass.run_command('g.region', n=reg_org['n'], s=reg_org['s'],
  393. e=reg_org['e'], w=reg_org['w'], align=input)
  394. # patch orig and fill map
  395. grass.message(_("Patching fill data into NULL areas..."))
  396. # we can use --o here as g.parser already checks on startup
  397. grass.run_command('r.patch', input=(input, prefix + 'filled'), output=output, overwrite=True)
  398. # restore the real region
  399. grass.del_temp_region()
  400. grass.message(_("Filled raster map is: %s") % output)
  401. # write cmd history:
  402. grass.raster_history(output)
  403. if len(failed_list) > 0:
  404. grass.warning(
  405. _("Following holes where not filled. Temporary maps with are left in place to allow examination of unfilled holes"))
  406. outlist = failed_list[0]
  407. for hole in failed_list[1:]:
  408. outlist = ', ' + outlist
  409. grass.message(outlist)
  410. grass.message(_("Done."))
  411. if __name__ == "__main__":
  412. options, flags = grass.parser()
  413. atexit.register(cleanup)
  414. main()