r.fillnulls.py 21 KB

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