r.fillnulls.py 19 KB

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