r.fillnulls.py 20 KB

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