r.fillnulls.py 19 KB

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