r.fillnulls.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. #% keywords: raster
  27. #% keywords: elevation
  28. #% keywords: 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. tmp_rmaps = list()
  90. tmp_vmaps = list()
  91. usermask = None
  92. mapset = None
  93. # what to do in case of user break:
  94. def cleanup():
  95. #delete internal mask and any TMP files:
  96. if len(tmp_vmaps) > 0:
  97. grass.run_command('g.remove', quiet = True, flags = 'fb', type = 'vect', pattern = tmp_vmaps)
  98. if len(tmp_rmaps) > 0:
  99. grass.run_command('g.remove', quiet = True, flags = 'fb', type = 'rast', pattern = tmp_rmaps)
  100. if usermask and mapset:
  101. if grass.find_file(usermask, mapset = mapset)['file']:
  102. grass.run_command('g.rename', quiet = True, rast = (usermask, 'MASK'), overwrite = True)
  103. def main():
  104. global usermask, mapset, tmp_rmaps, tmp_vmaps
  105. input = options['input']
  106. output = options['output']
  107. tension = options['tension']
  108. smooth = options['smooth']
  109. method = options['method']
  110. edge = int(options['edge'])
  111. segmax = int(options['segmax'])
  112. npmin = int(options['npmin'])
  113. quiet = True # FIXME
  114. mapset = grass.gisenv()['MAPSET']
  115. unique = str(os.getpid()) # Shouldn't we use temp name?
  116. prefix = 'r_fillnulls_%s_' % unique
  117. failed_list = list() # a list of failed holes. Caused by issues with v.surf.rst. Connected with #1813
  118. #check if input file exists
  119. if not grass.find_file(input)['file']:
  120. grass.fatal(_("Raster map <%s> not found") % input)
  121. # save original region
  122. reg_org = grass.region()
  123. # check if a MASK is already present
  124. # and remove it to not interfere with NULL lookup part
  125. # as we don't fill MASKed parts!
  126. if grass.find_file('MASK', mapset = mapset)['file']:
  127. usermask = "usermask_mask." + unique
  128. grass.message(_("A user raster mask (MASK) is present. Saving it..."))
  129. grass.run_command('g.rename', quiet = quiet, rast = ('MASK',usermask))
  130. #check if method is rst to use v.surf.rst
  131. if method == 'rst':
  132. # idea: filter all NULLS and grow that area(s) by 3 pixel, then
  133. # interpolate from these surrounding 3 pixel edge
  134. filling = prefix + 'filled'
  135. grass.use_temp_region()
  136. grass.run_command('g.region', align = input, quiet = quiet)
  137. region = grass.region()
  138. ns_res = region['nsres']
  139. ew_res = region['ewres']
  140. grass.message(_("Using RST interpolation..."))
  141. grass.message(_("Locating and isolating NULL areas..."))
  142. # creating binary (0/1) map
  143. if usermask:
  144. grass.message(_("Skipping masked raster parts"))
  145. grass.mapcalc("$tmp1 = if(isnull($input) && !($mask == 0 || isnull($mask)),1,null())",
  146. tmp1 = prefix + 'nulls', input = input, mask = usermask)
  147. else:
  148. grass.mapcalc("$tmp1 = if(isnull($input),1,null())",
  149. tmp1 = prefix + 'nulls', input = input)
  150. tmp_rmaps.append(prefix + 'nulls')
  151. # restoring user's mask, if present
  152. # to ignore MASKed original values
  153. if usermask:
  154. grass.message(_("Restoring user mask (MASK)..."))
  155. if grass.run_command('g.rename', quiet = quiet, rast = (usermask, 'MASK')) != 0:
  156. grass.warning(_("Failed to restore user MASK!"))
  157. usermask = None
  158. # grow identified holes by X pixels
  159. grass.message(_("Growing NULL areas"))
  160. tmp_rmaps.append(prefix + 'grown')
  161. if grass.run_command('r.grow', input = prefix + 'nulls', radius = edge + 0.01,
  162. old = 1, new = 1, out = prefix + 'grown', quiet = quiet) != 0:
  163. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  164. # assign unique IDs to each hole or hole system (holes closer than edge distance)
  165. grass.message(_("Assigning IDs to NULL areas"))
  166. tmp_rmaps.append(prefix + 'clumped')
  167. if grass.run_command('r.clump', input = prefix + 'grown', output = prefix + 'clumped', quiet = quiet) != 0:
  168. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  169. # get a list of unique hole cat's
  170. grass.mapcalc("$out = if(isnull($inp), null(), $clumped)",
  171. out = prefix + 'holes', inp = prefix + 'nulls', clumped = prefix + 'clumped')
  172. tmp_rmaps.append(prefix + 'holes')
  173. # use new IDs to identify holes
  174. if grass.run_command('r.to.vect', flags = 'v', input = prefix + 'holes', output = prefix + 'holes',
  175. type = 'area', quiet = quiet) != 0:
  176. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  177. tmp_vmaps.append(prefix + 'holes')
  178. # get a list of unique hole cat's
  179. cats_file_name = grass.tempfile(False)
  180. grass.run_command('v.db.select', flags = 'c', map = prefix + 'holes', columns = 'cat', file = cats_file_name, quiet = quiet)
  181. cat_list = list()
  182. cats_file = file(cats_file_name)
  183. for line in cats_file:
  184. cat_list.append(line.rstrip('\n'))
  185. cats_file.close()
  186. os.remove(cats_file_name)
  187. if len(cat_list) < 1:
  188. grass.fatal(_("Input map has no holes. Check region settings."))
  189. # GTC Hole is NULL area in a raster map
  190. grass.message(_("Processing %d map holes") % len(cat_list))
  191. first = True
  192. hole_n = 1
  193. for cat in cat_list:
  194. holename = prefix + 'hole_' + cat
  195. # GTC Hole is a NULL area in a raster map
  196. grass.message(_("Filling hole %s of %s") % (hole_n, len(cat_list)))
  197. hole_n = hole_n + 1
  198. # cut out only CAT hole for processing
  199. if grass.run_command('v.extract', input = prefix + 'holes', output = holename + '_pol',
  200. cats = cat, quiet = quiet) != 0:
  201. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  202. tmp_vmaps.append(holename + '_pol')
  203. # zoom to specific hole with a buffer of two cells around the hole to remove rest of data
  204. if grass.run_command('g.region', vect = holename + '_pol', align = input,
  205. w = 'w-%d' % (edge * 2 * ew_res), e = 'e+%d' % (edge * 2 * ew_res),
  206. n = 'n+%d' % (edge * 2 * ns_res), s = 's-%d' % (edge * 2 * ns_res),
  207. quiet = quiet) != 0:
  208. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  209. # remove temporary map to not overfill disk
  210. if grass.run_command('g.remove', flags = 'fb', type = 'vect', pattern = holename + '_pol', quiet = quiet) != 0:
  211. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  212. tmp_vmaps.remove(holename + '_pol')
  213. # copy only data around hole
  214. grass.mapcalc("$out = if($inp == $catn, $inp, null())",
  215. out = holename, inp = prefix + 'holes', catn = cat)
  216. tmp_rmaps.append(holename)
  217. # If here loop is split into two, next part of loop can be run in parallel
  218. # (except final result patching)
  219. # Downside - on large maps such approach causes large disk usage
  220. # grow hole border to get it's edge area
  221. tmp_rmaps.append(holename + '_grown')
  222. if grass.run_command('r.grow', input = holename, radius = edge + 0.01,
  223. old = -1, out = holename + '_grown', quiet = quiet) != 0:
  224. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  225. # no idea why r.grow old=-1 doesn't replace existing values with NULL
  226. grass.mapcalc("$out = if($inp == -1, null(), $dem)",
  227. out = holename + '_edges', inp = holename + '_grown', dem = input)
  228. tmp_rmaps.append(holename + '_edges')
  229. # convert to points for interpolation
  230. tmp_vmaps.append(holename)
  231. if grass.run_command('r.to.vect', input = holename + '_edges', output = holename,
  232. type = 'point', flags = 'z', quiet = quiet) != 0:
  233. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  234. # count number of points to control segmax parameter for interpolation:
  235. pointsnumber = grass.vector_info_topo(map = holename)['points']
  236. grass.verbose(_("Interpolating %d points") % pointsnumber)
  237. if pointsnumber < 2:
  238. grass.verbose(_("No points to interpolate"))
  239. failed_list.append(holename)
  240. continue
  241. # Avoid v.surf.rst warnings
  242. if pointsnumber < segmax:
  243. npmin = pointsnumber + 1
  244. segmax = pointsnumber
  245. # launch v.surf.rst
  246. tmp_rmaps.append(holename + '_dem')
  247. if grass.run_command('v.surf.rst', quiet = quiet, input = holename, elev = holename + '_dem',
  248. tension = tension, smooth = smooth,
  249. segmax = segmax, npmin = npmin) != 0:
  250. # GTC Hole is NULL area in a raster map
  251. grass.fatal(_("Failed to fill hole %s") % cat)
  252. # v.surf.rst sometimes fails with exit code 0
  253. # related bug #1813
  254. if not grass.find_file(holename + '_dem')['file']:
  255. try:
  256. tmp_rmaps.remove(holename)
  257. tmp_rmaps.remove(holename + '_grown')
  258. tmp_rmaps.remove(holename + '_edges')
  259. tmp_rmaps.remove(holename + '_dem')
  260. tmp_vmaps.remove(holename)
  261. except:
  262. pass
  263. grass.warning(_("Filling has failed silently. Leaving temporary maps with prefix <%s> for debugging.") % holename)
  264. failed_list.append(holename)
  265. continue
  266. # append hole result to interpolated version later used to patch into original DEM
  267. if first:
  268. tmp_rmaps.append(filling)
  269. grass.run_command('g.region', align = input, rast = holename + '_dem', quiet = quiet)
  270. grass.mapcalc("$out = if(isnull($inp), null(), $dem)",
  271. out = filling, inp = holename, dem = holename + '_dem')
  272. first = False
  273. else:
  274. tmp_rmaps.append(filling + '_tmp')
  275. grass.run_command('g.region', align = input, rast = (filling, holename + '_dem'), quiet = quiet)
  276. grass.mapcalc("$out = if(isnull($inp), if(isnull($fill), null(), $fill), $dem)",
  277. out = filling + '_tmp', inp = holename, dem = holename + '_dem', fill = filling)
  278. if grass.run_command('g.rename', rast = (filling + '_tmp', filling),
  279. overwrite = True, quiet = quiet) != 0:
  280. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  281. tmp_rmaps.remove(filling + '_tmp') # this map has been removed. No need for later cleanup.
  282. # remove temporary maps to not overfill disk
  283. try:
  284. tmp_rmaps.remove(holename)
  285. tmp_rmaps.remove(holename + '_grown')
  286. tmp_rmaps.remove(holename + '_edges')
  287. tmp_rmaps.remove(holename + '_dem')
  288. except:
  289. pass
  290. if grass.run_command('g.remove', quiet = quiet, flags = 'fb', type = 'rast', pattern =
  291. (holename, holename + '_grown', holename + '_edges', holename + '_dem')) != 0:
  292. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  293. try:
  294. tmp_vmaps.remove(holename)
  295. except:
  296. pass
  297. if grass.run_command('g.remove', quiet = quiet, flags = 'fb', type = 'vect', pattern = holename) != 0:
  298. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  299. #check if method is different from rst to use r.resamp.bspline
  300. if method != 'rst':
  301. grass.message(_("Using %s bspline interpolation") % method)
  302. # clone current region
  303. grass.use_temp_region()
  304. grass.run_command('g.region', align = input)
  305. reg = grass.region()
  306. # launch r.resamp.bspline
  307. tmp_rmaps.append(prefix + 'filled')
  308. if usermask:
  309. grass.run_command('r.resamp.bspline', input = input, mask = usermask,
  310. output = prefix + 'filled', method = method,
  311. ew_step = 3 * reg['ewres'], ns_step = 3 * reg['nsres'],
  312. _lambda = 0.01, flags = 'n')
  313. else:
  314. grass.run_command('r.resamp.bspline', input = input,
  315. output = prefix + 'filled', method = method,
  316. ew_step = 3 * reg['ewres'], ns_step = 3 * reg['nsres'],
  317. _lambda = 0.01, flags = 'n')
  318. # restoring user's mask, if present:
  319. if usermask:
  320. grass.message(_("Restoring user mask (MASK)..."))
  321. if grass.run_command('g.rename', quiet = quiet, rast = (usermask, 'MASK')) != 0:
  322. grass.warning(_("Failed to restore user MASK!"))
  323. usermask = None
  324. # set region to original extents, align to input
  325. grass.run_command('g.region', n = reg_org['n'], s = reg_org['s'],
  326. e = reg_org['e'], w = reg_org['w'], align = input)
  327. # patch orig and fill map
  328. grass.message(_("Patching fill data into NULL areas..."))
  329. # we can use --o here as g.parser already checks on startup
  330. grass.run_command('r.patch', input = (input,prefix + 'filled'), output = output, overwrite = True)
  331. # restore the real region
  332. grass.del_temp_region()
  333. grass.message(_("Filled raster map is: %s") % output)
  334. # write cmd history:
  335. grass.raster_history(output)
  336. if len(failed_list) > 0:
  337. grass.warning(_("Following holes where not filled. Temporary maps with are left in place to allow examination of unfilled holes"))
  338. outlist = failed_list[0]
  339. for hole in failed_list[1:]:
  340. outlist = ', ' + outlist
  341. grass.message(outlist)
  342. grass.message(_("Done."))
  343. if __name__ == "__main__":
  344. options, flags = grass.parser()
  345. atexit.register(cleanup)
  346. main()