r.fillnulls.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. # Add support to v.surf.bspline by Luca Delucchi
  12. # PURPOSE: fills NULL (no data areas) in raster maps
  13. # The script respects a user mask (MASK) if present.
  14. #
  15. # COPYRIGHT: (C) 2001-2012 by the GRASS Development Team
  16. #
  17. # This program is free software under the GNU General Public
  18. # License (>=v2). Read the file COPYING that comes with GRASS
  19. # for details.
  20. #
  21. #############################################################################
  22. #%module
  23. #% description: Fills no-data areas in raster maps using spline interpolation.
  24. #% keywords: raster
  25. #% keywords: elevation
  26. #% keywords: interpolation
  27. #%end
  28. #%option G_OPT_R_INPUT
  29. #%end
  30. #%option G_OPT_R_OUTPUT
  31. #%end
  32. #%option
  33. #% key: tension
  34. #% type: double
  35. #% description: Spline tension parameter
  36. #% required : no
  37. #% answer : 40.
  38. #%end
  39. #%option
  40. #% key: smooth
  41. #% type: double
  42. #% description: Spline smoothing parameter
  43. #% required : no
  44. #% answer : 0.1
  45. #%end
  46. #%option
  47. #% key: method
  48. #% type: string
  49. #% description: Interpolation method
  50. #% required : yes
  51. #% options : bilinear,bicubic,rst
  52. #% answer : rst
  53. #%end
  54. import sys
  55. import os
  56. import atexit
  57. import grass.script as grass
  58. vecttmp = None
  59. tmp1 = None
  60. usermask = None
  61. mapset = None
  62. # what to do in case of user break:
  63. def cleanup():
  64. #delete internal mask and any TMP files:
  65. if tmp1:
  66. rasts = [tmp1 + ext for ext in ['', '.buf', '_filled']]
  67. grass.run_command('g.remove', quiet = True, flags = 'f', rast = rasts)
  68. if vecttmp:
  69. grass.run_command('g.remove', quiet = True, flags = 'f', vect = vecttmp)
  70. grass.run_command('g.remove', quiet = True, rast = 'MASK')
  71. if usermask and mapset:
  72. if grass.find_file(usermask, mapset = mapset)['file']:
  73. grass.run_command('g.rename', quiet = True, rast = (usermask, 'MASK'))
  74. def main():
  75. global vecttmp, tmp1, usermask, mapset
  76. input = options['input']
  77. output = options['output']
  78. tension = options['tension']
  79. smooth = options['smooth']
  80. method = options['method']
  81. mapset = grass.gisenv()['MAPSET']
  82. unique = str(os.getpid())
  83. #check if input file exists
  84. if not grass.find_file(input)['file']:
  85. grass.fatal(_("<%s> does not exist.") % input)
  86. # check if a MASK is already present:
  87. usermask = "usermask_mask." + unique
  88. if grass.find_file('MASK', mapset = mapset)['file']:
  89. grass.message(_("A user raster mask (MASK) is present. Saving it..."))
  90. grass.run_command('g.rename', quiet = True, rast = ('MASK',usermask))
  91. #make a mask of NULL cells
  92. tmp1 = "r_fillnulls_" + unique
  93. #check if method is rst to use v.surf.rst
  94. if method == 'rst':
  95. # idea: filter all NULLS and grow that area(s) by 3 pixel, then
  96. # interpolate from these surrounding 3 pixel edge
  97. grass.message(_("Locating and isolating NULL areas..."))
  98. #creating 0/1 map:
  99. grass.mapcalc("$tmp1 = if(isnull($input),1,null())",
  100. tmp1 = tmp1, input = input)
  101. #generate a ring:
  102. # the buffer is set to three times the map resolution so you get nominally
  103. # three points around the edge. This way you interpolate into the hole with
  104. # a trained slope & curvature at the edges, otherwise you just get a flat plane.
  105. # With just a single row of cells around the hole you often get gaps
  106. # around the edges when distance > mean (.5 of the time? diagonals? worse
  107. # when ewres!=nsres).
  108. # r.buffer broken in trunk for latlon, disabled
  109. #reg = grass.region()
  110. #res = (float(reg['nsres']) + float(reg['ewres'])) * 3 / 2
  111. #if grass.run_command('r.buffer', input = tmp1, distances = res, out = tmp1 + '.buf') != 0:
  112. # much easier way: use r.grow with radius=3.01
  113. if grass.run_command('r.grow', input = tmp1, radius = 3.01,
  114. old = 1, new = 2, out = tmp1 + '.buf') != 0:
  115. grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
  116. grass.mapcalc("MASK = if($tmp1.buf == 2, 1, null())", tmp1 = tmp1)
  117. # now we only see the outlines of the NULL areas if looking at INPUT.
  118. # Use this outline (raster border) for interpolating the fill data:
  119. vecttmp = "vecttmp_fillnulls_" + unique
  120. grass.message(_("Creating interpolation points..."))
  121. ## use the -b flag to avoid topology building on big jobs?
  122. ## no, can't, 'g.region vect=' currently wants to see level 2
  123. if grass.run_command('r.to.vect', input = input, output = vecttmp,
  124. type = 'point', flags = 'z'):
  125. grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
  126. # count number of points to control segmax parameter for interpolation:
  127. pointsnumber = grass.vector_info_topo(map = vecttmp)['points']
  128. grass.message(_("Interpolating %d points") % pointsnumber)
  129. if pointsnumber < 2:
  130. grass.fatal(_("Not sufficient points to interpolate. Maybe no hole(s) to fill in the current map region?"))
  131. # remove internal MASK first -- WHY???? MN 10/2005
  132. grass.run_command('g.remove', quiet = True, rast = 'MASK')
  133. # print message is a usermask it was present
  134. if grass.find_file(usermask, mapset = mapset)['file']:
  135. grass.message(_("Using user mask while interpolating"))
  136. maskmap = usermask
  137. else:
  138. maskmap = None
  139. grass.message(_("Note: The following 'consider changing' warnings may be ignored."))
  140. # clone current region
  141. grass.use_temp_region()
  142. grass.run_command('g.region', vect = vecttmp, align = input)
  143. # set the max number before segmantation
  144. segmax = 600
  145. if pointsnumber > segmax:
  146. grass.message(_("Using segmentation for interpolation..."))
  147. segmax = None
  148. else:
  149. grass.message(_("Using no segmentation for interpolation as not needed..."))
  150. # launch v.surf.rst
  151. grass.message(_("Using RST interpolation..."))
  152. grass.run_command('v.surf.rst', input = vecttmp, elev = tmp1 + '_filled',
  153. zcol = 'value', tension = tension, smooth = smooth,
  154. maskmap = maskmap, segmax = segmax, flags = 'z')
  155. grass.message(_("Note: Above warnings may be ignored."))
  156. #check if method is different from rst to use r.resamp.bspline
  157. if method != 'rst':
  158. grass.message(_("Using %s bspline interpolation") % method)
  159. # clone current region
  160. grass.use_temp_region()
  161. grass.run_command('g.region', align = input)
  162. reg = grass.region()
  163. # launch r.resamp.bspline
  164. if grass.find_file(usermask, mapset = mapset)['file']:
  165. grass.run_command('r.resamp.bspline', input = input, mask = usermask,
  166. output = tmp1 + '_filled', method = method,
  167. se = 3 * reg['ewres'], sn = 3 * reg['nsres'],
  168. flags = 'n')
  169. else:
  170. grass.run_command('r.resamp.bspline', input = input,
  171. output = tmp1 + '_filled', method = method,
  172. se = 3 * reg['ewres'], sn = 3 * reg['nsres'],
  173. flags = 'n')
  174. # restoring user's mask, if present:
  175. if grass.find_file(usermask, mapset = mapset)['file']:
  176. grass.message(_("Restoring user mask (MASK)..."))
  177. grass.run_command('g.rename', quiet = True, rast = (usermask, 'MASK'))
  178. # patch orig and fill map
  179. grass.message(_("Patching fill data into NULL areas..."))
  180. # we can use --o here as g.parser already checks on startup
  181. grass.run_command('r.patch', input = (input,tmp1 + '_filled'), output = output, overwrite = True)
  182. # restore the real region
  183. grass.del_temp_region()
  184. grass.message(_("Filled raster map is: %s") % output)
  185. # write cmd history:
  186. grass.raster_history(output)
  187. grass.message(_("Done."))
  188. if __name__ == "__main__":
  189. options, flags = grass.parser()
  190. atexit.register(cleanup)
  191. main()