def smooth_map(raster, method, size): """ Parameters ---------- raster : method : size : Returns ------- Examples -------- """ # Build MASK for current category & high quality recreation areas msg = "Smoothing map '{m}'" grass.verbose(_(msg.format(m=raster))) r.neighbors( input=raster, output=raster, method=method, size=size, overwrite=True, quiet=True, )
def neighborhood_function(raster, method, size, distance_map): """ Parameters ---------- raster : Name of input raster map for which to apply r.neighbors method : Method for r.neighbors size : Size for r.neighbors distance : A distance map Returns ------- filtered_output : A neighborhood filtered raster map Examples -------- ... """ r.null(map=raster, null=0) # Set NULLs to 0 neighborhood_output = distance_map + "_" + method msg = "* Neighborhood operator '{method}' and size '{size}' for map '{name}'" msg = msg.format(method=method, size=size, name=neighborhood_output) grass.verbose(_(msg)) r.neighbors( input=raster, output=neighborhood_output, method=method, size=size, overwrite=True, ) scoring_function = "{neighborhood} * {distance}" scoring_function = scoring_function.format( neighborhood=neighborhood_output, distance=distance_map) filtered_output = distance_map filtered_output += "_" + method + "_" + str(size) neighborhood_function = EQUATION.format(result=filtered_output, expression=scoring_function) # --------------------------------------------------------------- grass.debug(_("*** Expression: {e}".format(e=neighborhood_function))) # --------------------------------------------------------------- grass.mapcalc(neighborhood_function, overwrite=True) # tmp_distance_map = filtered_output # r.compress(distance_map, flags='g') return filtered_output
def smooth_dem(DEM): """Smooth the DEM using an 11 cell averaging filter with gauss weighting of 3 radius""" smoothed = rand_id("smoothed{}".format(L + 1)) TMP_RAST[L].append(smoothed) r.neighbors(input=DEM, output=smoothed, size=11, gauss=3) return smoothed
def get_smoothed_dem(L, DEM): """Smooth the DEM using an 11 cell averaging filter with gauss weighting of 3 radius""" smoothed = "tmp_DEM_smoothed_step{L}".format(L=L+1) + \ ''.join([random.choice(string.ascii_letters + string.digits) for n in range(4)]) TMP_RAST[L].append(smoothed) # g = 4.3565 * math.exp(-(3 / 3.0)) r.neighbors(input=DEM, output=smoothed, size=11, gauss=3) return smoothed
def get_smoothed_dem(L, DEM): """Smooth the DEM using an 11 cell averaging filter with gauss weighting of 3 radius""" smoothed = "tmp_DEM_smoothed_step{L}".format(L=L+1) + \ ''.join([random.choice(string.ascii_letters + string.digits) for n in range(4)]) TMP_RAST[L].append(smoothed) #g = 4.3565 * math.exp(-(3 / 3.0)) r.neighbors(input=DEM, output=smoothed, size=11, gauss=3) return smoothed
def lee_filter(img, size, img_out): pid = str(os.getpid()) img_mean = 'tmp%s_img_mean' % pid img_sqr = 'tmp%s_img_sqr' % pid img_sqr_mean = 'tmp%s_img_sqr_mean' % pid img_variance = 'tmp%s_img_variance' % pid img_weights = 'tmp%s_img_weights' % pid # Local mean r.neighbors(input = img, size = size, method = 'average', output = img_mean) # Local square mean r.mapcalc("%s = %s^2" % (img_sqr, img)) r.neighbors(input = img_sqr, size = size, method = 'average', output = img_sqr_mean) # Local variance r.mapcalc("%s = %s - (%s^2)" % (img_variance, img_sqr_mean, img_mean)) # Overall variance return_univar = grass.read_command('r.univar', map = img, flags = 'ge') univar_stats = grass.parse_key_val(return_univar) overall_variance = univar_stats['variance'] # Weights r.mapcalc("%s = %s / (%s + %s)" % (img_weights, img_variance, img_variance, overall_variance)) # Output r.mapcalc("%s = %s + %s * (%s - %s)" % (img_out, img_mean, img_weights, img, img_mean)) # Cleanup grass.message(_("Cleaning up intermediate files...")) try: grass.run_command('g.remove', flags = 'f', quiet = False, type = 'raster', pattern = 'tmp*') except: "" return img_out
def lee_filter(img, size, img_out): pid = str(os.getpid()) img_mean = "tmp%s_img_mean" % pid img_sqr = "tmp%s_img_sqr" % pid img_sqr_mean = "tmp%s_img_sqr_mean" % pid img_variance = "tmp%s_img_variance" % pid img_weights = "tmp%s_img_weights" % pid # Local mean r.neighbors(input=img, size=size, method="average", output=img_mean) # Local square mean r.mapcalc("%s = %s^2" % (img_sqr, img)) r.neighbors(input=img_sqr, size=size, method="average", output=img_sqr_mean) # Local variance r.mapcalc("%s = %s - (%s^2)" % (img_variance, img_sqr_mean, img_mean)) # Overall variance return_univar = grass.read_command("r.univar", map=img, flags="ge") univar_stats = grass.parse_key_val(return_univar) overall_variance = univar_stats["variance"] # Weights r.mapcalc("%s = %s / (%s + %s)" % (img_weights, img_variance, img_variance, overall_variance)) # Output r.mapcalc("%s = %s + %s * (%s - %s)" % (img_out, img_mean, img_weights, img, img_mean)) # Cleanup grass.message(_("Cleaning up intermediate files...")) try: grass.run_command("g.remove", flags="f", quiet=False, type="raster", pattern="tmp*") except: """ """ return img_out
def smooth_map(raster, method, size): """ Parameters ---------- raster : method : size : Returns ------- Examples -------- """ r.neighbors( input=raster, output=raster, method=method, size=size, overwrite=True, quiet=True, )
def main(): soilloss = options['soilloss'] soilloss9 = soilloss.split('@')[0] + '.9' soilloss3 = soilloss.split('@')[0] + '.3' colorschema = options['colorschema'] flag_u = flags['u'] flag_f = flags['f'] quiet = True if gscript.verbosity() > 2: quiet=False #color shemes - contents: classrules = { 'soillossbare9' : {}, 'soillossbare3' : {}, 'soillossgrow9' : {}, 'cfactor6' : {}, 'kfactor6' : {} } colorrules = { 'soillossbare9': {}, 'soillossbare3': {}, 'soillossbare' : {}, 'soillossgrow9' : {}, 'soillossgrow' : {}, 'cfactor6' : {}, 'cfactor' : {}, 'kfactor6' : {}, 'kfactor' : {} } # (c) Gisler 2010 classrules['soillossbare9'] = '\n '.join([ "0 thru 20 = 1 < 20", "20 thru 30 = 2 20 - 30", "30 thru 40 = 3 30 - 40", "40 thru 55 = 4 40 - 55", "55 thru 100 = 5 55 - 100", "100 thru 150 = 6 100 - 150", "150 thru 250 = 7 150 - 250", "250 thru 500 = 8 250 - 500", "500 thru 50000 = 9 > 500", ]) # (c) Gisler 2010 classrules['soillossbare3'] = '\n '.join([ "0 thru 30 = 1 keine Gefährdung", "30 thru 55 = 2 Gefährdung", "55 thru 50000 = 3 grosse Gefährdung", ]) # (c) BLW 2011 colorrules['soillossbare9'] = '\n '.join([ "1 0:102:0", "2 51:153:0", "3 204:255:0", "4 255:255:0", "5 255:102:0", "6 255:0:0", "7 204:0:0", "8 153:0:0", "9 102:0:0", ]) # (c) BLW 2011 colorrules['soillossbare3'] = '\n '.join([ "1 51:153:0", "2 255:255:0", "3 255:0:0" ]) # (c) BLW 2011 colorrules['soillossbare'] = '\n '.join([ "0 0:102:0", "20 51:153:0", "30 204:255:0", "40 255:255:0", "55 255:102:0", "100 255:0:0", "150 204:0:0", "250 153:0:0", "500 102:0:0", "5000 102:0:0" ]) # (c) Gisler 2010 colorrules['soillossgrow9'] = '\n '.join([ "1 69:117:183", "2 115:146:185", "3 163:179:189", "4 208:216:193", "5 255:255:190", "6 252:202:146", "7 245:153:106", "8 233:100:70", "9 213:47:39" ]) # (c) Gisler 2010 colorrules['soillossgrow9'] = '\n '.join([ "1 69:117:183", "2 115:146:185", "3 163:179:189", "4 208:216:193", "5 255:255:190", "6 252:202:146", "7 245:153:106", "8 233:100:70", "9 213:47:39" ]) # (c) Gisler 2010 colorrules['soillossgrow3'] = '\n '.join([ "1 69:117:183", "2 163:179:189", "3 208:216:193", "4 245:153:106" ]) # (c) Gisler 2010 colorrules['soillossgrow'] = '\n '.join([ "0 69:117:183", "1 115:146:185", "2 163:179:189", "4 208:216:193", "7.5 255:255:190", "10 252:202:146", "15 245:153:106", "20 233:100:70", "30 213:47:39", "300 213:47:39" ]) # (c) Gisler 2010 classrules['soillossgrow9'] = '\n '.join([ "0 thru 1 = 1 < 1 ", "1 thru 2 = 2 1 - 2 ", "2 thru 4 = 3 2 - 4 ", "4 thru 7.5 = 4 4 - 7.5", "7.5 thru 10 = 5 7.5 - 10", "10 thru 15 = 6 10 - 15", "15 thru 20 = 7 15 - 20", "20 thru 30 = 8 20 - 30", "30 thru 5000 = 9 > 30" ]) # (c) Gisler 2010 classrules['soillossgrow3'] = '\n '.join([ "0 thru 2 = 1 Toleranz mittelgründige Böden", "2 thru 4 = 2 Toleranz tiefgründige Böden", "4 thru 7.5 = 3 leichte Überschreitung", "7.5 thru 5000 = 4 starke Überschreitung" ]) # Gisler 2010 colorrules['cfactor6'] = '\n '.join([ "1 56:145:37", "2 128:190:91", "3 210:233:153", "4 250:203:147", "5 225:113:76", "6 186:20:20" ]) # Gisler 2010 colorrules['cfactor'] = '\n '.join([ "0.00 56:145:37", "0.01 128:190:91", "0.05 210:233:153", "0.1 250:203:147", "0.15 225:113:76", "0.2 186:20:20", "1 186:20:20", ]) # (c) Gisler 2010 classrules['kfactor5'] = '\n '.join([ "0 thru 0.20 = 1 < 0.20", "0.20 thru 0.25 = 2 0.20 - 0.25", "0.25 thru 0.30 = 3 0.25 - 0.3", "0.3 thru 0.35 = 4 0.3 - 0.35", "0.35 thru 1 = 5 > 0.30" ]) # (c) Gisler 2010 colorrules['kfactor6'] = '\n '.join([ "1 15:70:15", "2 98:131:52", "3 204:204:104", "4 151:101:50", "5 98:21:15" ]) # (c) Gisler 2010 colorrules['kfactor'] = '\n '.join([ "0.00 15:70:15", "0.20 98:131:52", "0.25 204:204:104", "0.30 151:101:50", "0.35 98:21:15" ]) # own definitions colorrules['cpmax'] = '\n '.join([ "0.01 102:0:0", "0.01 153:0:0", "0.02 204:0:0", "0.04 255:0:0", "0.06 255:102:0", "0.08 255:255:0", "0.10 204:255:0", "0.12 51:153:0", "0.15 0:102:0", "1000.00 0:102:0" ]) classrules9 = '\n '.join([ "0 thru 20 = 1 <20", "20 thru 30 = 2 20 - 30", "30 thru 40 = 3 30 - 40", "40 thru 55 = 4 40 - 55", "55 thru 100 = 5 55 - 100", "100 thru 150 = 6 100 - 150", "150 thru 250 = 7 150 - 250", "250 thru 500 = 8 250 - 500", "500 thru 50000 = 9 >500", ]) if colorschema == 'soillossbare': classrules9 = classrules['soillossbare9'] colorrules9 = colorrules['soillossbare9'] classrules3 = classrules['soillossbare3'] colorrules3 = colorrules['soillossbare3'] colorrules = colorrules['soillossbare'] if colorschema == 'soillossgrow': classrules9 = classrules['soillossgrow9'] colorrules9 = colorrules['soillossgrow9'] classrules3 = classrules['soillossgrow3'] colorrules3 = colorrules['soillossgrow3'] colorrules = colorrules['soillossgrow'] r.reclass(input=soilloss, rules='-', stdin = classrules9, output=soilloss9) r.colors(map = soilloss9, rules = '-', stdin = colorrules9, quiet = quiet) r.reclass(input=soilloss, rules='-', stdin = classrules3, output=soilloss3) r.colors(map = soilloss3, rules = '-', stdin = colorrules3, quiet = quiet) if flag_f: soilloss3f = soilloss3 + 'f' r.neighbors(method='mode', input=soilloss3, selection=soilloss3, output=soilloss3f, size=7) soilloss3 = soilloss3f if flag_u: r.colors(map = soilloss, rules = '-', stdin = colorrules, quiet = quiet)
def main(): # options and flags options, flags = gs.parser() input_raster = options["input"] minradius = int(options["minradius"]) maxradius = int(options["maxradius"]) steps = int(options["steps"]) output_raster = options["output"] region = Region() res = np.mean([region.nsres, region.ewres]) # some checks if "@" in output_raster: output_raster = output_raster.split("@")[0] if maxradius <= minradius: gs.fatal("maxradius must be greater than minradius") if steps < 2: gs.fatal("steps must be greater than 1") # calculate radi for generalization radi = np.logspace(np.log(minradius), np.log(maxradius), steps, base=np.exp(1), dtype=np.int) radi = np.unique(radi) sizes = radi * 2 + 1 # multiscale calculation ztpi_maps = list() for step, (radius, size) in enumerate(zip(radi[::-1], sizes[::-1])): gs.message( "Calculating the TPI at radius {radius}".format(radius=radius)) # generalize the dem step_res = res * size step_res_pretty = str(step_res).replace(".", "_") generalized_dem = gs.tempname(4) if size > 15: step_dem = gs.tempname(4) gg.region(res=str(step_res)) gr.resamp_stats( input=input_raster, output=step_dem, method="average", flags="w", ) gr.resamp_rst( input=step_dem, ew_res=res, ns_res=res, elevation=generalized_dem, quiet=True, ) region.write() gg.remove(type="raster", name=step_dem, flags="f", quiet=True) else: gr.neighbors(input=input_raster, output=generalized_dem, size=size) # calculate the tpi tpi = gs.tempname(4) gr.mapcalc(expression="{x} = {a} - {b}".format( x=tpi, a=input_raster, b=generalized_dem)) gg.remove(type="raster", name=generalized_dem, flags="f", quiet=True) # standardize the tpi raster_stats = gr.univar(map=tpi, flags="g", stdout_=PIPE).outputs.stdout raster_stats = parse_key_val(raster_stats) tpi_mean = float(raster_stats["mean"]) tpi_std = float(raster_stats["stddev"]) ztpi = gs.tempname(4) ztpi_maps.append(ztpi) RAST_REMOVE.append(ztpi) gr.mapcalc(expression="{x} = ({a} - {mean})/{std}".format( x=ztpi, a=tpi, mean=tpi_mean, std=tpi_std)) gg.remove(type="raster", name=tpi, flags="f", quiet=True) # integrate if step > 1: tpi_updated2 = gs.tempname(4) gr.mapcalc("{x} = if(abs({a}) > abs({b}), {a}, {b})".format( a=ztpi_maps[step], b=tpi_updated1, x=tpi_updated2)) RAST_REMOVE.append(tpi_updated2) tpi_updated1 = tpi_updated2 else: tpi_updated1 = ztpi_maps[0] RAST_REMOVE.pop() gg.rename(raster=(tpi_updated2, output_raster), quiet=True) # set color theme with RasterRow(output_raster) as src: color_rules = """{minv} blue -1 0:34:198 0 255:255:255 1 255:0:0 {maxv} 110:15:0 """ color_rules = color_rules.format(minv=src.info.min, maxv=src.info.max) gr.colors(map=output_raster, rules="-", stdin_=color_rules, quiet=True)
# Cut maps for mm in maps: expr = i+'_'+mm+' = '+mm+'@PERMANENT' print expr r.mapcalc(expr, overwrite = True) # distance from roads r.grow_distance(input = i+'_'+'gROADS_v1_americas_rast', distance = i+'_'+'gROADS_v1_dist_from_roads_meters_exp', metric = 'geodesic', flags = 'm', overwrite = True) # road density size = 9990/30 # 10 km = 333 pixels r.neighbors(input = i+'_'+'gROADS_v1_americas_rast', output = i+'_'+'gROADS_v1_road_density_pixels_per_100km2', method = 'sum', size = size, overwrite = True) r.mapcalc(i+'_'+'gROADS_v1_road_density_km_per_100km2_exp = '+i+'_'+'gROADS_v1_road_density_pixels_per_100km2 * 30 / 1000', overwrite = True) # Hansen bin r.mapcalc(i+'_Neotropic_Hansen_percenttreecoverd_2000_wgs84_gt0_binary = if(Neotropic_Hansen_percenttreecoverd_2000_wgs84 > 0, 1, 0)', overwrite = True) # Hansen correspondent year expr = i+'_Neotropic_Hansen_percenttreecoverd_2000_wgs84_gt0_binary_year_exp = if('+i+'_Neotropical_Hansen_treecoverlossperyear_wgs84_2017 > 0 && '+ \ i+'_Neotropical_Hansen_treecoverlossperyear_wgs84_2017 < '+str(yy)+', 0, '+i+'_Neotropic_Hansen_percenttreecoverd_2000_wgs84_gt0_binary)' r.mapcalc(expr, overwrite = True) # NPP ext in the end r.mapcalc(i+'_MOD17A3_Science_NPP_mean_00_15_exp = '+i+'_MOD17A3_Science_NPP_mean_00_15', overwrite = True) # export maps