r.fillnulls.py 16 KB

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