r.fillnulls.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. <<<<<<< 1ca5ade0f050cc22722fdcbb57af91135215607e
  126. quiet = True # FIXME
  127. =======
  128. quiet = True # FIXME
  129. >>>>>>> scripts modules: support python3
  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. npmin = pointsnumber + 1
  307. segmax = pointsnumber
  308. # launch v.surf.rst
  309. tmp_rmaps.append(holename + '_dem')
  310. try:
  311. grass.run_command('v.surf.rst', quiet=quiet,
  312. input=holename, elev=holename + '_dem',
  313. tension=tension, smooth=smooth,
  314. segmax=segmax, npmin=npmin)
  315. except CalledModuleError:
  316. # GTC Hole is NULL area in a raster map
  317. grass.fatal(_("Failed to fill hole %s") % cat)
  318. # v.surf.rst sometimes fails with exit code 0
  319. # related bug #1813
  320. if not grass.find_file(holename + '_dem')['file']:
  321. try:
  322. tmp_rmaps.remove(holename)
  323. tmp_rmaps.remove(holename + '_grown')
  324. tmp_rmaps.remove(holename + '_edges')
  325. tmp_rmaps.remove(holename + '_dem')
  326. tmp_vmaps.remove(holename)
  327. except:
  328. pass
  329. grass.warning(
  330. _("Filling has failed silently. Leaving temporary maps "
  331. "with prefix <%s> for debugging.") %
  332. holename)
  333. failed_list.append(holename)
  334. continue
  335. # append hole result to interpolated version later used to patch into original DEM
  336. if first:
  337. tmp_rmaps.append(filling)
  338. grass.run_command('g.region', align=input, raster=holename + '_dem', quiet=quiet)
  339. grass.mapcalc("$out = if(isnull($inp), null(), $dem)",
  340. out=filling, inp=holename, dem=holename + '_dem')
  341. first = False
  342. else:
  343. tmp_rmaps.append(filling + '_tmp')
  344. grass.run_command(
  345. 'g.region', align=input, raster=(
  346. filling, holename + '_dem'), quiet=quiet)
  347. grass.mapcalc(
  348. "$out = if(isnull($inp), if(isnull($fill), null(), $fill), $dem)",
  349. out=filling + '_tmp',
  350. inp=holename,
  351. dem=holename + '_dem',
  352. fill=filling)
  353. try:
  354. grass.run_command('g.rename',
  355. raster=(filling + '_tmp', filling),
  356. overwrite=True, quiet=quiet)
  357. except CalledModuleError:
  358. grass.fatal(
  359. _("abandoned. Removing temporary maps, restoring user "
  360. "mask if needed:"))
  361. # this map has been removed. No need for later cleanup.
  362. tmp_rmaps.remove(filling + '_tmp')
  363. # remove temporary maps to not overfill disk
  364. try:
  365. tmp_rmaps.remove(holename)
  366. tmp_rmaps.remove(holename + '_grown')
  367. tmp_rmaps.remove(holename + '_edges')
  368. tmp_rmaps.remove(holename + '_dem')
  369. except:
  370. pass
  371. try:
  372. grass.run_command('g.remove', quiet=quiet,
  373. flags='fb', type='raster',
  374. name=(holename,
  375. holename + '_grown',
  376. holename + '_edges',
  377. holename + '_dem'))
  378. except CalledModuleError:
  379. grass.fatal(_("abandoned. Removing temporary maps, restoring "
  380. "user mask if needed:"))
  381. try:
  382. tmp_vmaps.remove(holename)
  383. except:
  384. pass
  385. try:
  386. grass.run_command('g.remove', quiet=quiet, flags='fb',
  387. type='vector', name=holename)
  388. except CalledModuleError:
  389. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  390. # check if method is different from rst to use r.resamp.bspline
  391. if method != 'rst':
  392. grass.message(_("Using %s bspline interpolation") % method)
  393. # clone current region
  394. grass.use_temp_region()
  395. grass.run_command('g.region', align=input)
  396. reg = grass.region()
  397. # launch r.resamp.bspline
  398. tmp_rmaps.append(prefix + 'filled')
  399. if usermask:
  400. grass.run_command('r.resamp.bspline', input=input, mask=usermask,
  401. output=prefix + 'filled', method=method,
  402. ew_step=3 * reg['ewres'], ns_step=3 * reg['nsres'],
  403. lambda_=lambda_, flags='n')
  404. else:
  405. grass.run_command('r.resamp.bspline', input=input,
  406. output=prefix + 'filled', method=method,
  407. ew_step=3 * reg['ewres'], ns_step=3 * reg['nsres'],
  408. lambda_=lambda_, flags='n')
  409. # restoring user's mask, if present:
  410. if usermask:
  411. grass.message(_("Restoring user mask (MASK)..."))
  412. try:
  413. grass.run_command('g.rename', quiet=quiet, raster=(usermask, 'MASK'))
  414. except CalledModuleError:
  415. grass.warning(_("Failed to restore user MASK!"))
  416. usermask = None
  417. # set region to original extents, align to input
  418. grass.run_command('g.region', n=reg_org['n'], s=reg_org['s'],
  419. e=reg_org['e'], w=reg_org['w'], align=input)
  420. # patch orig and fill map
  421. grass.message(_("Patching fill data into NULL areas..."))
  422. # we can use --o here as g.parser already checks on startup
  423. grass.run_command('r.patch', input=(input, prefix + 'filled'),
  424. output=output, overwrite=True)
  425. # restore the real region
  426. grass.del_temp_region()
  427. grass.message(_("Filled raster map is: %s") % output)
  428. # write cmd history:
  429. grass.raster_history(output)
  430. if len(failed_list) > 0:
  431. grass.warning(
  432. _("Following holes where not filled. Temporary maps with are left "
  433. "in place to allow examination of unfilled holes"))
  434. outlist = failed_list[0]
  435. for hole in failed_list[1:]:
  436. outlist = ', ' + outlist
  437. grass.message(outlist)
  438. grass.message(_("Done."))
  439. if __name__ == "__main__":
  440. options, flags = grass.parser()
  441. atexit.register(cleanup)
  442. main()