예제 #1
0
def calc_slope(elevation):
    """Calculates slope angle in percent using r.slope.aspect

    Parameters
    ----------
    elevation : str
        Name of the GRASS raster map with the elevation data.

    Returns
    -------
    slope : str
        Name of the output slope map.
    """
    slope = rand_id("slope{}".format(L + 1))
    TMP_RAST[L].append(slope)
    r.slope_aspect(elevation=elevation,
                   slope=slope,
                   flags="e",
                   format="percent",
                   quiet=True)

    return slope
예제 #2
0
def main():
    # user specified variables
    dem = options["elevation"]
    slope = options["slope"]
    aspect = options["aspect"]
    neighborhood_size = options["size"]
    output = options["output"]
    nprocs = int(options["nprocs"])
    exponent = float(options["exponent"])

    # check for valid neighborhood sizes
    neighborhood_size = neighborhood_size.split(",")
    neighborhood_size = [int(i) for i in neighborhood_size]

    if any([True for i in neighborhood_size if i % 2 == 0]):
        gs.fatal(
            "Invalid size - neighborhood sizes have to consist of odd numbers")

    if min(neighborhood_size) == 1:
        gs.fatal("Neighborhood sizes have to be > 1")

    # determine nprocs
    if nprocs < 0:
        n_cores = mp.cpu_count()
        nprocs = n_cores - (nprocs + 1)

    # temporary raster map names for slope, aspect, x, y, z components
    if slope == "":
        slope_raster = create_tempname("tmpSlope_")
    else:
        slope_raster = slope

    if aspect == "":
        aspect_raster = create_tempname("tmpAspect_")
    else:
        aspect_raster = aspect

    z_raster = create_tempname("tmpzRaster_")
    x_raster = create_tempname("tmpxRaster_")
    y_raster = create_tempname("tmpyRaster_")

    # create slope and aspect rasters
    if slope == "" or aspect == "":
        gs.message("Calculating slope and aspect...")
        gr.slope_aspect(
            elevation=dem,
            slope=slope_raster,
            aspect=aspect_raster,
            format="degrees",
            precision="FCELL",
            zscale=1.0,
            min_slope=0.0,
            quiet=True,
        )

    # calculate x y and z rasters
    # note - GRASS sin/cos functions differ from ArcGIS which expects input grid in radians
    # whereas GRASS functions expect degrees
    # no need to convert slope and aspect to radians as in the original ArcGIS script
    x_expr = "{x} = float( sin({a}) * sin({b}) )".format(x=x_raster,
                                                         a=aspect_raster,
                                                         b=slope_raster)

    y_expr = "{y} = float( cos({a}) * sin({b}) )".format(y=y_raster,
                                                         a=aspect_raster,
                                                         b=slope_raster)

    z_expr = "{z} = float( cos({a}) )".format(z=z_raster, a=slope_raster)

    # calculate x, y, z components (parallel)
    gs.message("Calculating x, y, and z rasters...")

    mapcalc = Module("r.mapcalc", run_=False)
    queue = ParallelModuleQueue(nprocs=nprocs)

    mapcalc1 = copy.deepcopy(mapcalc)
    m = mapcalc1(expression=x_expr)
    queue.put(m)

    mapcalc2 = copy.deepcopy(mapcalc)
    m = mapcalc2(expression=y_expr)
    queue.put(m)

    mapcalc3 = copy.deepcopy(mapcalc)
    m = mapcalc3(expression=z_expr)
    queue.put(m)

    queue.wait()

    # calculate x, y, z neighborhood sums (parallel)
    gs.message(
        "Calculating sums of x, y, and z rasters in selected neighborhoods...")

    x_sum_list = []
    y_sum_list = []
    z_sum_list = []

    neighbors = Module("r.neighbors", overwrite=True, run_=False)
    queue = ParallelModuleQueue(nprocs=nprocs)

    for size in neighborhood_size:
        # create temporary raster names for neighborhood x, y, z sums
        x_sum_raster = create_tempname("tmpxSumRaster_")
        x_sum_list.append(x_sum_raster)

        y_sum_raster = create_tempname("tmpySumRaster_")
        y_sum_list.append(y_sum_raster)

        z_sum_raster = create_tempname("tmpzSumRaster_")
        z_sum_list.append(z_sum_raster)

        # create weights
        mat = idw_weights(size, exponent)

        # queue jobs for x, y, z neighborhood sums
        neighbors_xsum = copy.deepcopy(neighbors)
        n = neighbors_xsum(
            input=x_raster,
            output=x_sum_raster,
            method="average",
            size=size,
            weight=mat,
            stdin=mat,
        )
        queue.put(n)

        neighbors_ysum = copy.deepcopy(neighbors)
        n = neighbors_ysum(
            input=y_raster,
            output=y_sum_raster,
            method="average",
            size=size,
            weight=mat,
        )
        queue.put(n)

        neighbors_zsum = copy.deepcopy(neighbors)
        n = neighbors_zsum(
            input=z_raster,
            output=z_sum_raster,
            method="average",
            size=size,
            weight=mat,
        )
        queue.put(n)

    queue.wait()

    # calculate the resultant vector and final ruggedness raster
    # modified from the original script to multiple each SumRaster by the n neighborhood
    # cells to get the sum
    gs.message("Calculating the final ruggedness rasters...")

    mapcalc = Module("r.mapcalc", run_=False)
    queue = ParallelModuleQueue(nprocs=nprocs)
    vrm_list = []

    for x_sum_raster, y_sum_raster, z_sum_raster, size in zip(
            x_sum_list, y_sum_list, z_sum_list, neighborhood_size):

        if len(neighborhood_size) > 1:
            vrm_name = "_".join([output, str(size)])
        else:
            vrm_name = output

        vrm_list.append(vrm_name)

        vrm_expr = "{x} = float(1-( (sqrt(({a}*{d})^2 + ({b}*{d})^2 + ({c}*{d})^2) / {d})))".format(
            x=vrm_name,
            a=x_sum_raster,
            b=y_sum_raster,
            c=z_sum_raster,
            d=int(size) * int(size),
        )
        mapcalc1 = copy.deepcopy(mapcalc)
        m = mapcalc1(expression=vrm_expr)
        queue.put(m)

    queue.wait()

    # set colors
    gr.colors(flags="e", map=vrm_list, color="ryb")

    # set metadata
    for vrm, size in zip(vrm_list, neighborhood_size):
        title = "Vector Ruggedness Measure (size={size})".format(size=size)
        gr.support(map=vrm, title=title)

    return 0
예제 #3
0
                  streams=streams_all,
                  streams_modflow=streams_MODFLOW,
                  dem_modflow=DEM_MODFLOW,
                  overwrite=True)

# GSFLOW reaches: intersection of segments and grid
v.gsflow_reaches(segment_input=segments,
                 grid_input=MODFLOW_grid,
                 elevation=DEM,
                 output=reaches,
                 overwrite=True)

# GSFLOW HRU parameters
r.slope_aspect(elevation=DEM,
               slope=slope,
               aspect=aspect,
               format='percent',
               zscale=0.01,
               overwrite=True)
v.gsflow_hruparams(input=basins_inbasin,
                   elevation=DEM,
                   output=HRUs,
                   slope=slope,
                   aspect=aspect,
                   overwrite=True)

# GSFLOW gravity reservoirs
v.gsflow_gravres(hru_input=HRUs,
                 grid_input=MODFLOW_grid,
                 output=gravity_reservoirs,
                 overwrite=True)
예제 #4
0
    * chi?
    * remember, these are meant to work ASSUMING STREAM POWER
        --> and therefore probably assuming bedrock, though all quite
            fuzzy in stream-power land anyway.
"""

# Full set of commands:
elevation = 'srtm3'
#slope = 'srtm.slope'
#streams = 'srtm.stream
# or THRESH if not STREAMS -- in km**2
thresh = 10  # 1 km2 = minimum catchment size

# Made to work on a projected coordinate system PROJECTED!
reg = region.Region()
"""
# Slope first, easy
r.slope_aspect(elevation=elevation, slope='tmp', format='percent', overwrite=True)
r.mapcalc('slope = tmp/100.', overwrite=True)

# Assuming you work in meters. ASSUMING!
# Have to include output name or write to a temporary file, FOR ALL!
r.mapcalc('cellArea_meters2 = '+str(reg.nsres)+' * '+str(reg.ewres), overwrite=True)
r.mapcalc("cellArea_km2 = cellArea_meters2 / 10^6", overwrite=True)

# Works with MFD too!
# Not really. Drainage from one catchment goes to multiple basins
r.watershed(elevation=elevation, flow='cellArea_km2', accumulation='drainageArea_km2', drainage='drainageDirection', stream='streams_tmp', threshold=thresh, flags='s', overwrite=True)
# Remove areas of negative (offmap) accumulation
r.mapcalc('drainageArea_km2 = drainageArea_km2 * (drainageArea_km2 > 0)', overwrite=True)
r.null(map='drainageArea_km2', setnull=0)
# or THRESH if not STREAMS -- in km**2
thresh = 0.2  # 10 km2 = minimum catchment size
thresh = 10000  # m2

# Made to work on a projected coordinate system PROJECTED!
reg = region.Region()

##############
# BEFOREHAND #
##############
# These also will generate inputs: code to run beforehand

# Slope first, easy
print "Computing slope with r.slope.aspect. Slope in unitless decimal values."
r.slope_aspect(elevation=elevation,
               slope='tmp',
               format='percent',
               overwrite=True)
r.mapcalc('slope = tmp/100.', overwrite=True)

# Assuming you work in meters. ASSUMING!
# Have to include output name or write to a temporary file, FOR ALL!
r.mapcalc('cellArea_meters2 = ' + str(reg.nsres) + ' * ' + str(reg.ewres),
          overwrite=True)
r.mapcalc("cellArea_km2 = cellArea_meters2 / 10^6", overwrite=True)

print "Running r.watershed"
r.watershed(elevation=elevation,
            flow='cellArea_meters2',
            accumulation='drainageArea_m2',
            drainage='drainageDirection',
            stream='streams',
예제 #6
0
파일: example.py 프로젝트: bluegeo/mower
from mower import GrassSession

DEM = "/home/mperry/projects/shortcreek/dem/dem.img"

with GrassSession(DEM) as gs:
    from grass.pygrass.modules.shortcuts import raster

    # Import/Link to External GDAL data
    raster.external(input=DEM, output="dem")

    # Perform calculations
    raster.mapcalc(expression="demft=dem*3.28084")
    raster.slope_aspect(elevation="demft", slope="slope", aspect="aspect")

    # Export from GRASS to GDAL
    from grass.pygrass.gis import Mapset
    m = Mapset()
    for r in m.glist('rast'):
    	if r == "dem":
    		# don't save the original
    		continue

    	raster.out_gdal(r, format="GTiff", output="/tmp/{}.tif".format(r), overwrite=True)
예제 #7
0
 def slopestats():
     slopemap = Rast(maps['elevation'].name + '.slope')
     r.slope_aspect(elevation=maps['elevation'].name, slope=slopemap.name, format='percent') 
     print('\n \n Statistics for slope <%s> (slope in %%): '%(slopemap.name))
     rsoillossstats(soilloss=slopemap.name, map=parcelmap.name, parcelnumcol='id')
예제 #8
0
파일: example.py 프로젝트: kavgan/mower
from mower import GrassSession

DEM = "/home/mperry/projects/shortcreek/dem/dem.img"

with GrassSession(DEM) as gs:
    from grass.pygrass.modules.shortcuts import raster

    # Import/Link to External GDAL data
    raster.external(input=DEM, output="dem")

    # Perform calculations
    raster.mapcalc(expression="demft=dem*3.28084")
    raster.slope_aspect(elevation="demft", slope="slope", aspect="aspect")

    # Export from GRASS to GDAL
    from grass.pygrass.gis import Mapset
    m = Mapset()
    for r in m.glist('rast'):
        if r == "dem":
            # don't save the original
            continue

        raster.out_gdal(r,
                        format="GTiff",
                        output="/tmp/{}.tif".format(r),
                        overwrite=True)