r.fillnulls.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 "
  181. "user mask if needed:"))
  182. # assign unique IDs to each hole or hole system (holes closer than edge distance)
  183. grass.message(_("Assigning IDs to NULL areas"))
  184. tmp_rmaps.append(prefix + 'clumped')
  185. try:
  186. grass.run_command(
  187. 'r.clump',
  188. input=prefix +
  189. 'grown',
  190. output=prefix +
  191. 'clumped',
  192. quiet=quiet)
  193. except CalledModuleError:
  194. grass.fatal(_("abandoned. Removing temporary map, restoring "
  195. "user mask if needed:"))
  196. # get a list of unique hole cat's
  197. grass.mapcalc("$out = if(isnull($inp), null(), $clumped)",
  198. out=prefix + 'holes', inp=prefix + 'nulls', clumped=prefix + 'clumped')
  199. tmp_rmaps.append(prefix + 'holes')
  200. # use new IDs to identify holes
  201. try:
  202. grass.run_command('r.to.vect', flags='v',
  203. input=prefix + 'holes', output=prefix + 'holes',
  204. type='area', quiet=quiet)
  205. except:
  206. grass.fatal(_("abandoned. Removing temporary maps, restoring "
  207. "user mask if needed:"))
  208. tmp_vmaps.append(prefix + 'holes')
  209. # get a list of unique hole cat's
  210. cats_file_name = grass.tempfile(False)
  211. grass.run_command(
  212. 'v.db.select',
  213. flags='c',
  214. map=prefix + 'holes',
  215. columns='cat',
  216. file=cats_file_name,
  217. quiet=quiet)
  218. cat_list = list()
  219. cats_file = file(cats_file_name)
  220. for line in cats_file:
  221. cat_list.append(line.rstrip('\n'))
  222. cats_file.close()
  223. os.remove(cats_file_name)
  224. if len(cat_list) < 1:
  225. grass.fatal(_("Input map has no holes. Check region settings."))
  226. # GTC Hole is NULL area in a raster map
  227. grass.message(_("Processing %d map holes") % len(cat_list))
  228. first = True
  229. hole_n = 1
  230. for cat in cat_list:
  231. holename = prefix + 'hole_' + cat
  232. # GTC Hole is a NULL area in a raster map
  233. grass.message(_("Filling hole %s of %s") % (hole_n, len(cat_list)))
  234. hole_n = hole_n + 1
  235. # cut out only CAT hole for processing
  236. try:
  237. grass.run_command('v.extract', input=prefix + 'holes',
  238. output=holename + '_pol',
  239. cats=cat, quiet=quiet)
  240. except CalledModuleError:
  241. grass.fatal(_("abandoned. Removing temporary maps, restoring "
  242. "user mask if needed:"))
  243. tmp_vmaps.append(holename + '_pol')
  244. # zoom to specific hole with a buffer of two cells around the hole to
  245. # remove rest of data
  246. try:
  247. grass.run_command('g.region',
  248. vector=holename + '_pol', align=input,
  249. w='w-%d' % (edge * 2 * ew_res),
  250. e='e+%d' % (edge * 2 * ew_res),
  251. n='n+%d' % (edge * 2 * ns_res),
  252. s='s-%d' % (edge * 2 * ns_res),
  253. quiet=quiet)
  254. except CalledModuleError:
  255. grass.fatal(_("abandoned. Removing temporary maps, restoring "
  256. "user mask if needed:"))
  257. # remove temporary map to not overfill disk
  258. try:
  259. grass.run_command('g.remove', flags='fb', type='vector',
  260. name=holename + '_pol', quiet=quiet)
  261. except CalledModuleError:
  262. grass.fatal(_("abandoned. Removing temporary maps, restoring "
  263. "user mask if needed:"))
  264. tmp_vmaps.remove(holename + '_pol')
  265. # copy only data around hole
  266. grass.mapcalc("$out = if($inp == $catn, $inp, null())",
  267. out=holename, inp=prefix + 'holes', catn=cat)
  268. tmp_rmaps.append(holename)
  269. # If here loop is split into two, next part of loop can be run in parallel
  270. # (except final result patching)
  271. # Downside - on large maps such approach causes large disk usage
  272. # grow hole border to get it's edge area
  273. tmp_rmaps.append(holename + '_grown')
  274. try:
  275. grass.run_command('r.grow', input=holename, radius=edge + 0.01,
  276. old=-1, out=holename + '_grown', quiet=quiet)
  277. except CalledModuleError:
  278. grass.fatal(_("abandoned. Removing temporary map, restoring "
  279. "user mask if needed:"))
  280. # no idea why r.grow old=-1 doesn't replace existing values with NULL
  281. grass.mapcalc("$out = if($inp == -1, null(), $dem)",
  282. out=holename + '_edges', inp=holename + '_grown', dem=input)
  283. tmp_rmaps.append(holename + '_edges')
  284. # convert to points for interpolation
  285. tmp_vmaps.append(holename)
  286. try:
  287. grass.run_command('r.to.vect',
  288. input=holename + '_edges', output=holename,
  289. type='point', flags='z', quiet=quiet)
  290. except CalledModuleError:
  291. grass.fatal(_("abandoned. Removing temporary maps, restoring "
  292. "user mask if needed:"))
  293. # count number of points to control segmax parameter for interpolation:
  294. pointsnumber = grass.vector_info_topo(map=holename)['points']
  295. grass.verbose(_("Interpolating %d points") % pointsnumber)
  296. if pointsnumber < 2:
  297. grass.verbose(_("No points to interpolate"))
  298. failed_list.append(holename)
  299. continue
  300. # Avoid v.surf.rst warnings
  301. if pointsnumber < segmax:
  302. npmin = pointsnumber + 1
  303. segmax = pointsnumber
  304. # launch v.surf.rst
  305. tmp_rmaps.append(holename + '_dem')
  306. try:
  307. grass.run_command('v.surf.rst', quiet=quiet,
  308. input=holename, elev=holename + '_dem',
  309. tension=tension, smooth=smooth,
  310. segmax=segmax, npmin=npmin)
  311. except CalledModuleError:
  312. # GTC Hole is NULL area in a raster map
  313. grass.fatal(_("Failed to fill hole %s") % cat)
  314. # v.surf.rst sometimes fails with exit code 0
  315. # related bug #1813
  316. if not grass.find_file(holename + '_dem')['file']:
  317. try:
  318. tmp_rmaps.remove(holename)
  319. tmp_rmaps.remove(holename + '_grown')
  320. tmp_rmaps.remove(holename + '_edges')
  321. tmp_rmaps.remove(holename + '_dem')
  322. tmp_vmaps.remove(holename)
  323. except:
  324. pass
  325. grass.warning(
  326. _("Filling has failed silently. Leaving temporary maps "
  327. "with prefix <%s> for debugging.") %
  328. holename)
  329. failed_list.append(holename)
  330. continue
  331. # append hole result to interpolated version later used to patch into original DEM
  332. if first:
  333. tmp_rmaps.append(filling)
  334. grass.run_command('g.region', align=input, raster=holename + '_dem', quiet=quiet)
  335. grass.mapcalc("$out = if(isnull($inp), null(), $dem)",
  336. out=filling, inp=holename, dem=holename + '_dem')
  337. first = False
  338. else:
  339. tmp_rmaps.append(filling + '_tmp')
  340. grass.run_command(
  341. 'g.region', align=input, raster=(
  342. filling, holename + '_dem'), quiet=quiet)
  343. grass.mapcalc(
  344. "$out = if(isnull($inp), if(isnull($fill), null(), $fill), $dem)",
  345. out=filling + '_tmp',
  346. inp=holename,
  347. dem=holename + '_dem',
  348. fill=filling)
  349. try:
  350. grass.run_command('g.rename',
  351. raster=(filling + '_tmp', filling),
  352. overwrite=True, quiet=quiet)
  353. except CalledModuleError:
  354. grass.fatal(
  355. _("abandoned. Removing temporary maps, restoring user "
  356. "mask if needed:"))
  357. # this map has been removed. No need for later cleanup.
  358. tmp_rmaps.remove(filling + '_tmp')
  359. # remove temporary maps to not overfill disk
  360. try:
  361. tmp_rmaps.remove(holename)
  362. tmp_rmaps.remove(holename + '_grown')
  363. tmp_rmaps.remove(holename + '_edges')
  364. tmp_rmaps.remove(holename + '_dem')
  365. except:
  366. pass
  367. try:
  368. grass.run_command('g.remove', quiet=quiet,
  369. flags='fb', type='raster',
  370. name=(holename,
  371. holename + '_grown',
  372. holename + '_edges',
  373. holename + '_dem'))
  374. except CalledModuleError:
  375. grass.fatal(_("abandoned. Removing temporary maps, restoring "
  376. "user mask if needed:"))
  377. try:
  378. tmp_vmaps.remove(holename)
  379. except:
  380. pass
  381. try:
  382. grass.run_command('g.remove', quiet=quiet, flags='fb',
  383. type='vector', name=holename)
  384. except CalledModuleError:
  385. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  386. # check if method is different from rst to use r.resamp.bspline
  387. if method != 'rst':
  388. grass.message(_("Using %s bspline interpolation") % method)
  389. # clone current region
  390. grass.use_temp_region()
  391. grass.run_command('g.region', align=input)
  392. reg = grass.region()
  393. # launch r.resamp.bspline
  394. tmp_rmaps.append(prefix + 'filled')
  395. if usermask:
  396. grass.run_command('r.resamp.bspline', input=input, mask=usermask,
  397. output=prefix + 'filled', method=method,
  398. ew_step=3 * reg['ewres'], ns_step=3 * reg['nsres'],
  399. lambda_=lambda_, flags='n')
  400. else:
  401. grass.run_command('r.resamp.bspline', input=input,
  402. output=prefix + 'filled', method=method,
  403. ew_step=3 * reg['ewres'], ns_step=3 * reg['nsres'],
  404. lambda_=lambda_, flags='n')
  405. # restoring user's mask, if present:
  406. if usermask:
  407. grass.message(_("Restoring user mask (MASK)..."))
  408. try:
  409. grass.run_command('g.rename', quiet=quiet, raster=(usermask, 'MASK'))
  410. except CalledModuleError:
  411. grass.warning(_("Failed to restore user MASK!"))
  412. usermask = None
  413. # set region to original extents, align to input
  414. grass.run_command('g.region', n=reg_org['n'], s=reg_org['s'],
  415. e=reg_org['e'], w=reg_org['w'], align=input)
  416. # patch orig and fill map
  417. grass.message(_("Patching fill data into NULL areas..."))
  418. # we can use --o here as g.parser already checks on startup
  419. grass.run_command('r.patch', input=(input, prefix + 'filled'),
  420. output=output, overwrite=True)
  421. # restore the real region
  422. grass.del_temp_region()
  423. grass.message(_("Filled raster map is: %s") % output)
  424. # write cmd history:
  425. grass.raster_history(output)
  426. if len(failed_list) > 0:
  427. grass.warning(
  428. _("Following holes where not filled. Temporary maps with are left "
  429. "in place to allow examination of unfilled holes"))
  430. outlist = failed_list[0]
  431. for hole in failed_list[1:]:
  432. outlist = ', ' + outlist
  433. grass.message(outlist)
  434. grass.message(_("Done."))
  435. if __name__ == "__main__":
  436. options, flags = grass.parser()
  437. atexit.register(cleanup)
  438. main()