r.fillnulls.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. #!/usr/bin/env python
  2. #
  3. ############################################################################
  4. #
  5. # MODULE: r.fillnulls
  6. # AUTHOR(S): Markus Neteler <neteler itc it>
  7. # Updated to GRASS 5.7 by Michael Barton
  8. # Updated to GRASS 6.0 by Markus Neteler
  9. # Ring improvements by Hamish Bowman
  10. # Converted to Python by Glynn Clements
  11. # PURPOSE: fills NULL (no data areas) in raster maps
  12. # The script respects a user mask (MASK) if present.
  13. #
  14. # COPYRIGHT: (C) 2001,2004-2005,2008 by the GRASS Development Team
  15. #
  16. # This program is free software under the GNU General Public
  17. # License (>=v2). Read the file COPYING that comes with GRASS
  18. # for details.
  19. #
  20. #############################################################################
  21. #%module
  22. #% description: Fills no-data areas in raster maps using splines interpolation.
  23. #% keywords: raster
  24. #% keywords: elevation
  25. #% keywords: interpolation
  26. #%end
  27. #%option G_OPT_R_INPUT
  28. #%end
  29. #%option G_OPT_R_OUTPUT
  30. #%end
  31. #%option
  32. #% key: tension
  33. #% type: double
  34. #% description: Spline tension parameter
  35. #% required : no
  36. #% answer : 40.
  37. #%end
  38. #%option
  39. #% key: smooth
  40. #% type: double
  41. #% description: Spline smoothing parameter
  42. #% required : no
  43. #% answer : 0.1
  44. #%end
  45. import sys
  46. import os
  47. import atexit
  48. import grass.script as grass
  49. vecttmp = None
  50. tmp1 = None
  51. usermask = None
  52. mapset = None
  53. # what to do in case of user break:
  54. def cleanup():
  55. #delete internal mask and any TMP files:
  56. if tmp1:
  57. rasts = [tmp1 + ext for ext in ['', '.buf', '_filled']]
  58. grass.run_command('g.remove', flags = 'f', rast = rasts)
  59. if vecttmp:
  60. grass.run_command('g.remove', flags = 'f', vect = vecttmp)
  61. grass.run_command('g.remove', rast = 'MASK')
  62. if usermask and mapset:
  63. if grass.find_file(usermask, mapset = mapset)['file']:
  64. grass.run_command('g.rename', rast = (usermask, 'MASK'))
  65. def main():
  66. global vecttmp, tmp1, usermask, mapset
  67. input = options['input']
  68. output = options['output']
  69. tension = options['tension']
  70. smooth = options['smooth']
  71. mapset = grass.gisenv()['MAPSET']
  72. unique = str(os.getpid())
  73. #check if input file exists
  74. if not grass.find_file(input)['file']:
  75. grass.fatal(_("<%s> does not exist.") % input)
  76. # check if a MASK is already present:
  77. usermask = "usermask_mask." + unique
  78. if grass.find_file('MASK', mapset = mapset)['file']:
  79. grass.message(_("A user raster mask (MASK) is present. Saving it..."))
  80. grass.run_command('g.rename', rast = ('MASK',usermask))
  81. #make a mask of NULL cells
  82. tmp1 = "r_fillnulls_" + unique
  83. # idea: filter all NULLS and grow that area(s) by 3 pixel, then
  84. # interpolate from these surrounding 3 pixel edge
  85. grass.message(_("Locating and isolating NULL areas..."))
  86. #creating 0/1 map:
  87. grass.mapcalc("$tmp1 = if(isnull($input),1,null())",
  88. tmp1 = tmp1, input = input)
  89. #generate a ring:
  90. # the buffer is set to three times the map resolution so you get nominally
  91. # three points around the edge. This way you interpolate into the hole with
  92. # a trained slope & curvature at the edges, otherwise you just get a flat plane.
  93. # With just a single row of cells around the hole you often get gaps
  94. # around the edges when distance > mean (.5 of the time? diagonals? worse
  95. # when ewres!=nsres).
  96. # r.buffer broken in trunk for latlon, disabled
  97. #reg = grass.region()
  98. #res = (float(reg['nsres']) + float(reg['ewres'])) * 3 / 2
  99. #if grass.run_command('r.buffer', input = tmp1, distances = res, out = tmp1 + '.buf') != 0:
  100. # much easier way: use r.grow with radius=3.01
  101. if grass.run_command('r.grow', input = tmp1, radius = 3.01, old = 1, new = 2, out = tmp1 + '.buf') != 0:
  102. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  103. grass.mapcalc("MASK=if($tmp1.buf==2,1,null())", tmp1 = tmp1)
  104. # now we only see the outlines of the NULL areas if looking at INPUT.
  105. # Use this outline (raster border) for interpolating the fill data:
  106. vecttmp = "vecttmp_fillnulls_" + unique
  107. grass.message(_("Creating interpolation points..."))
  108. if grass.run_command('r.to.vect', input = input, output = vecttmp, feature = 'point'):
  109. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  110. # count number of points to control segmax parameter for interpolation:
  111. pointsnumber = grass.vector_info_topo(map = vecttmp)['points']
  112. grass.message(_("Interpolating %d points") % pointsnumber)
  113. if pointsnumber < 2:
  114. grass.fatal(_("Not sufficient points to interpolate. Maybe no hole(s) to fill in the current map region?"))
  115. grass.message(_("Note: The following warnings may be ignored."))
  116. # remove internal MASK first -- WHY???? MN 10/2005
  117. grass.run_command('g.remove', rast = 'MASK')
  118. if grass.find_file(usermask, mapset = mapset)['file']:
  119. grass.message(_("Using user mask while interpolating"))
  120. maskmap = usermask
  121. else:
  122. maskmap = None
  123. segmax = 600
  124. if pointsnumber > segmax:
  125. grass.message(_("Using segmentation for interpolation..."))
  126. segmax = None
  127. else:
  128. grass.message(_("Using no segmentation for interpolation as not needed..."))
  129. grass.run_command('v.surf.rst', input = vecttmp, elev = tmp1 + '_filled',
  130. zcol = 'value', tension = tension, smooth = smooth,
  131. maskmap = maskmap, segmax = segmax)
  132. grass.message(_("Note: Above warnings may be ignored."))
  133. # restoring user's mask, if present:
  134. if grass.find_file(usermask, mapset = mapset)['file']:
  135. grass.message(_("Restoring user mask (MASK)..."))
  136. grass.run_command('g.rename', rast = (usermask, 'MASK'))
  137. # patch orig and fill map
  138. grass.message(_("Patching fill data into NULL areas..."))
  139. # we can use --o here as g.parser already checks on startup
  140. grass.run_command('r.patch', input = (input,tmp1 + '_filled'), output = output, overwrite = True)
  141. grass.message(_("Filled raster map is: %s") % output)
  142. # write cmd history:
  143. grass.raster_history(output)
  144. grass.message(_("Done."))
  145. if __name__ == "__main__":
  146. options, flags = grass.parser()
  147. atexit.register(cleanup)
  148. main()