r.fillnulls.py 19 KB

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