r.fillnulls.py 18 KB

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