r.fillnulls.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. # Add support to v.surf.bspline by Luca Delucchi
  12. # Per hole filling with RST by Maris Nartiss
  13. # PURPOSE: fills NULL (no data areas) in raster maps
  14. # The script respects a user mask (MASK) if present.
  15. #
  16. # COPYRIGHT: (C) 2001-2012 by the GRASS Development Team
  17. #
  18. # This program is free software under the GNU General Public
  19. # License (>=v2). Read the file COPYING that comes with GRASS
  20. # for details.
  21. #
  22. #############################################################################
  23. #%module
  24. #% description: Fills no-data areas in raster maps using spline interpolation.
  25. #% keywords: raster
  26. #% keywords: elevation
  27. #% keywords: interpolation
  28. #%end
  29. #%option G_OPT_R_INPUT
  30. #%end
  31. #%option G_OPT_R_OUTPUT
  32. #%end
  33. #%option
  34. #% key: tension
  35. #% type: double
  36. #% description: Spline tension parameter
  37. #% required : no
  38. #% answer : 40.
  39. #% guisection: RST options
  40. #%end
  41. #%option
  42. #% key: smooth
  43. #% type: double
  44. #% description: Spline smoothing parameter
  45. #% required : no
  46. #% answer : 0.1
  47. #% guisection: RST options
  48. #%end
  49. #%option
  50. #% key: edge
  51. #% type: integer
  52. #% description: Width of hole edge used for interpolation (in cells)
  53. #% required : no
  54. #% answer : 3
  55. #% options : 2-100
  56. #% guisection: RST options
  57. #%end
  58. #%option
  59. #% key: method
  60. #% type: string
  61. #% description: Interpolation method
  62. #% required : yes
  63. #% options : linear,cubic,rst
  64. #% answer : rst
  65. #%end
  66. import sys
  67. import os
  68. import atexit
  69. import grass.script as grass
  70. tmp_rmaps = list()
  71. tmp_vmaps = list()
  72. usermask = None
  73. mapset = None
  74. # what to do in case of user break:
  75. def cleanup():
  76. #delete internal mask and any TMP files:
  77. if len(tmp_vmaps) > 0:
  78. grass.run_command('g.remove', quiet = True, flags = 'f', vect = tmp_vmaps)
  79. if len(tmp_rmaps) > 0:
  80. grass.run_command('g.remove', quiet = True, flags = 'f', rast = tmp_rmaps)
  81. if usermask and mapset:
  82. if grass.find_file(usermask, mapset = mapset)['file']:
  83. grass.run_command('g.rename', quiet = True, rast = (usermask, 'MASK'), overwrite = True)
  84. def main():
  85. global usermask, mapset, tmp_rmaps, tmp_vmaps
  86. input = options['input']
  87. output = options['output']
  88. tension = options['tension']
  89. smooth = options['smooth']
  90. method = options['method']
  91. edge = int(options['edge'])
  92. quiet = True # FIXME
  93. mapset = grass.gisenv()['MAPSET']
  94. unique = str(os.getpid()) # Shouldn't we use temp name?
  95. prefix = 'r_fillnulls_%s_' % unique
  96. failed_list = list() # a list of failed holes. Caused by issues with v.surf.rst. Connected with #1813
  97. #check if input file exists
  98. if not grass.find_file(input)['file']:
  99. grass.fatal(_("Map <%s> does not exist.") % input)
  100. # save original region
  101. reg_org = grass.region()
  102. # check if a MASK is already present
  103. # and remove it to not interfere with NULL lookup part
  104. # as we don't fill MASKed parts!
  105. if grass.find_file('MASK', mapset = mapset)['file']:
  106. usermask = "usermask_mask." + unique
  107. grass.message(_("A user raster mask (MASK) is present. Saving it..."))
  108. grass.run_command('g.rename', quiet = quiet, rast = ('MASK',usermask))
  109. #check if method is rst to use v.surf.rst
  110. if method == 'rst':
  111. # idea: filter all NULLS and grow that area(s) by 3 pixel, then
  112. # interpolate from these surrounding 3 pixel edge
  113. filling = prefix + 'filled'
  114. grass.use_temp_region()
  115. grass.run_command('g.region', align = input, quiet = quiet)
  116. region = grass.region()
  117. ns_res = region['nsres']
  118. ew_res = region['ewres']
  119. grass.message(_("Using RST interpolation..."))
  120. grass.message(_("Locating and isolating NULL areas..."))
  121. # creating binary (0/1) map
  122. if usermask:
  123. grass.message(_("Skipping masked raster parts"))
  124. grass.mapcalc("$tmp1 = if(isnull($input) && !($mask == 0 || isnull($mask)),1,null())",
  125. tmp1 = prefix + 'nulls', input = input, mask = usermask)
  126. else:
  127. grass.mapcalc("$tmp1 = if(isnull($input),1,null())",
  128. tmp1 = prefix + 'nulls', input = input)
  129. tmp_rmaps.append(prefix + 'nulls')
  130. # restoring user's mask, if present
  131. # to ignore MASKed original values
  132. if usermask:
  133. grass.message(_("Restoring user mask (MASK)..."))
  134. if grass.run_command('g.rename', quiet = quiet, rast = (usermask, 'MASK')) != 0:
  135. grass.warning(_("Failed to restore user MASK!"))
  136. usermask = None
  137. # grow identified holes by X pixels
  138. grass.message(_("Growing NULL areas"))
  139. tmp_rmaps.append(prefix + 'grown')
  140. if grass.run_command('r.grow', input = prefix + 'nulls', radius = edge + 0.01,
  141. old = 1, new = 1, out = prefix + 'grown', quiet = quiet) != 0:
  142. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  143. # assign unique IDs to each hole or hole system (holes closer than edge distance)
  144. grass.message(_("Assigning IDs to NULL areas"))
  145. tmp_rmaps.append(prefix + 'clumped')
  146. if grass.run_command('r.clump', input = prefix + 'grown', output = prefix + 'clumped', quiet = quiet) != 0:
  147. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  148. # use new IDs to identify holes
  149. grass.mapcalc("$out = if(isnull($inp), null(), $clumped)",
  150. out = prefix + 'holes', inp = prefix + 'nulls', clumped = prefix + 'clumped')
  151. tmp_rmaps.append(prefix + 'holes')
  152. # get a list of unique hole cat's
  153. cats_file_name = grass.tempfile(True)
  154. cats_file = file(cats_file_name, 'w')
  155. grass.run_command('r.stats', flags = 'n', input = prefix + 'holes', stdout = cats_file, quiet = quiet)
  156. cats_file.close()
  157. cat_list = list()
  158. cats_file = file(cats_file_name)
  159. for line in cats_file:
  160. cat_list.append(line.rstrip('\n'))
  161. cats_file.close()
  162. os.remove(cats_file_name)
  163. if len(cat_list) < 1:
  164. grass.fatal(_("Input map has no holes. Check region settings."))
  165. # GTC Hole is NULL area in a raster map
  166. grass.message(_("Processing %d map holes") % len(cat_list))
  167. first = True
  168. for cat in cat_list:
  169. holename = prefix + 'hole_' + cat
  170. # GTC Hole is a NULL area in a raster map
  171. grass.message(_("Filling hole %s of %s") % (cat, len(cat_list)))
  172. # cut out only CAT hole for processing
  173. if grass.run_command('g.region', rast = prefix + 'holes', align = input, quiet = quiet) != 0:
  174. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  175. grass.mapcalc("$out = if($inp == $catn, $inp, null())",
  176. out = prefix + 'tmp_hole', inp = prefix + 'holes', catn = cat)
  177. # zoom to specific hole to remove rest of data
  178. if grass.run_command('g.region', zoom = prefix + 'tmp_hole', align = input, quiet = quiet) != 0:
  179. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  180. # increase region a bit to fit edge zone
  181. if grass.run_command('g.region', align = input,
  182. w = 'w-%d' % (edge * 2 * ew_res), e = 'e+%d' % (edge * 2 * ew_res),
  183. n = 'n+%d' % (edge * 2 * ns_res), s = 's-%d' % (edge * 2 * ns_res),
  184. quiet = quiet) != 0:
  185. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  186. # copy only data around hole
  187. grass.mapcalc("$out = $inp", out = holename, inp = prefix + 'tmp_hole')
  188. # remove temporary map to not overfill disk
  189. if grass.run_command('g.remove', flags = 'f', rast = prefix + 'tmp_hole', quiet = quiet) != 0:
  190. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  191. tmp_rmaps.append(holename)
  192. # If here loop is split into two, next part of loop can be run in parallel
  193. # (except final result patching)
  194. # Downside - on large maps such approach causes large disk usage
  195. # grow hole border to get it's edge area
  196. tmp_rmaps.append(holename + '_grown')
  197. if grass.run_command('r.grow', input = holename, radius = edge + 0.01,
  198. old = -1, out = holename + '_grown', quiet = quiet) != 0:
  199. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  200. # no idea why r.grow old=-1 doesn't replace existing values with NULL
  201. grass.mapcalc("$out = if($inp == -1, null(), $dem)",
  202. out = holename + '_edges', inp = holename + '_grown', dem = input)
  203. tmp_rmaps.append(holename + '_edges')
  204. # convert to points for interpolation
  205. tmp_vmaps.append(holename)
  206. if grass.run_command('r.to.vect', input = holename + '_edges', output = holename,
  207. type = 'point', flags = 'z', quiet = quiet) != 0:
  208. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  209. # count number of points to control segmax parameter for interpolation:
  210. pointsnumber = grass.vector_info_topo(map = holename)['points']
  211. grass.verbose(_("Interpolating %d points") % pointsnumber)
  212. if pointsnumber < 2:
  213. grass.verbose(_("No points to interpolate"))
  214. failed_list.append(holename)
  215. continue
  216. grass.message(_("Note: The following warnings about number of points for interpolation may be ignored."))
  217. # set the max number before segmentation
  218. # npmin and segmax values were choosen by fair guess and thus are superior to all other values ;)
  219. segmax = 100
  220. npmin = 300
  221. if pointsnumber < 600:
  222. npmin = pointsnumber
  223. segmax = pointsnumber
  224. # launch v.surf.rst
  225. tmp_rmaps.append(holename + '_dem')
  226. if grass.run_command('v.surf.rst', quiet = quiet, input = holename, elev = holename + '_dem',
  227. tension = tension, smooth = smooth,
  228. segmax = segmax, npmin = npmin) != 0:
  229. # GTC Hole is NULL area in a raster map
  230. grass.fatal(_("Failed to fill hole %s") % cat)
  231. # v.surf.rst sometimes fails with exit code 0
  232. # related bug #1813
  233. if not grass.find_file(holename + '_dem')['file']:
  234. try:
  235. tmp_rmaps.remove(holename)
  236. tmp_rmaps.remove(holename + '_grown')
  237. tmp_rmaps.remove(holename + '_edges')
  238. tmp_rmaps.remove(holename + '_dem')
  239. tmp_vmaps.remove(holename)
  240. except:
  241. pass
  242. grass.warning(_("Filling has failed silently. Leaving temporary maps with prefix <%s> for debugging.") % holename)
  243. failed_list.append(holename)
  244. continue
  245. # append hole result to interpolated version later used to patch into original DEM
  246. if first:
  247. tmp_rmaps.append(filling)
  248. grass.run_command('g.region', align = input, rast = holename + '_dem', quiet = quiet)
  249. grass.mapcalc("$out = if(isnull($inp), null(), $dem)",
  250. out = filling, inp = holename, dem = holename + '_dem')
  251. first = False
  252. else:
  253. tmp_rmaps.append(filling + '_tmp')
  254. grass.run_command('g.region', align = input, rast = (filling, holename + '_dem'), quiet = quiet)
  255. grass.mapcalc("$out = if(isnull($inp), if(isnull($fill), null(), $fill), $dem)",
  256. out = filling + '_tmp', inp = holename, dem = holename + '_dem', fill = filling)
  257. if grass.run_command('g.rename', rast = (filling + '_tmp', filling),
  258. overwrite = True, quiet = quiet) != 0:
  259. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  260. tmp_rmaps.remove(filling + '_tmp') # this map has been removed. No need for later cleanup.
  261. # remove temporary maps to not overfill disk
  262. try:
  263. tmp_rmaps.remove(holename)
  264. tmp_rmaps.remove(holename + '_grown')
  265. tmp_rmaps.remove(holename + '_edges')
  266. tmp_rmaps.remove(holename + '_dem')
  267. except:
  268. pass
  269. if grass.run_command('g.remove', quiet = quiet, flags = 'f', rast =
  270. (holename, holename + '_grown', holename + '_edges', holename + '_dem')) != 0:
  271. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  272. try:
  273. tmp_vmaps.remove(holename)
  274. except:
  275. pass
  276. if grass.run_command('g.remove', quiet = quiet, flags = 'f', vect = holename) != 0:
  277. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  278. #check if method is different from rst to use r.resamp.bspline
  279. if method != 'rst':
  280. grass.message(_("Using %s bspline interpolation") % method)
  281. # clone current region
  282. grass.use_temp_region()
  283. grass.run_command('g.region', align = input)
  284. reg = grass.region()
  285. # launch r.resamp.bspline
  286. tmp_rmaps.append(prefix + 'filled')
  287. if usermask:
  288. grass.run_command('r.resamp.bspline', input = input, mask = usermask,
  289. output = prefix + 'filled', method = method,
  290. se = 3 * reg['ewres'], sn = 3 * reg['nsres'],
  291. _lambda = 0.01, flags = 'n')
  292. else:
  293. grass.run_command('r.resamp.bspline', input = input,
  294. output = prefix + 'filled', method = method,
  295. se = 3 * reg['ewres'], sn = 3 * reg['nsres'],
  296. _lambda = 0.01, flags = 'n')
  297. # restoring user's mask, if present:
  298. if usermask:
  299. grass.message(_("Restoring user mask (MASK)..."))
  300. if grass.run_command('g.rename', quiet = quiet, rast = (usermask, 'MASK')) != 0:
  301. grass.warning(_("Failed to restore user MASK!"))
  302. usermask = None
  303. # set region to original extents, align to input
  304. grass.run_command('g.region', n = reg_org['n'], s = reg_org['s'],
  305. e = reg_org['e'], w = reg_org['w'], align = input)
  306. # patch orig and fill map
  307. grass.message(_("Patching fill data into NULL areas..."))
  308. # we can use --o here as g.parser already checks on startup
  309. grass.run_command('r.patch', input = (input,prefix + 'filled'), output = output, overwrite = True)
  310. # restore the real region
  311. grass.del_temp_region()
  312. grass.message(_("Filled raster map is: %s") % output)
  313. # write cmd history:
  314. grass.raster_history(output)
  315. if len(failed_list) > 0:
  316. grass.warning(_("Following holes where not filled. Temporary maps with are left in place to allow examination of unfilled holes"))
  317. outlist = failed_list[0]
  318. for hole in failed_list[1:]:
  319. outlist = ', ' + outlist
  320. grass.message(outlist)
  321. grass.message(_("Done."))
  322. if __name__ == "__main__":
  323. options, flags = grass.parser()
  324. atexit.register(cleanup)
  325. main()