r.fillnulls.py 21 KB

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