Ejemplo n.º 1
0
def set_reference(descriptionflag = None):
    if options['raster_reference']:
        reference = options['raster_reference']
        refname = reference
    elif options['vector_reference'] and options['column']:
        savedregion = grass.tempname(12)
        grass.run_command('g.region', save=savedregion)
        grass.run_command('g.region', raster=options['classification'])
        reference = grass.tempname(12)
        kwargs = {
            'input': options['vector_reference'],
            'output': reference,
            'use': 'attr',
            'attribute_column': options['column']
        }
        if options['label_column']:
            kwargs['label_column'] = options['label_column']
        grass.run_command('v.to.rast', quiet=True, **kwargs)
        refname = options['vector_reference'] + ' with column ' + options['column']
        # reset region
        grass.run_command('g.region', region=savedregion, quiet=True)
        # remove region
        grass.run_command('g.remove', flags='f', type='region', name=savedregion, quiet=True)
    else:
        if not descriptionflag:
            grass.fatal("Either <raster_reference> or <vector_reference> and <column> must be indicated")
    return reference, refname
Ejemplo n.º 2
0
def set_reference(descriptionflag=None):
    if options["raster_reference"]:
        reference = options["raster_reference"]
        refname = reference
    elif options["vector_reference"] and options["column"]:
        savedregion = grass.tempname(12)
        grass.run_command("g.region", save=savedregion)
        grass.run_command("g.region", raster=options["classification"])
        reference = grass.tempname(12)
        kwargs = {
            "input": options["vector_reference"],
            "output": reference,
            "use": "attr",
            "attribute_column": options["column"],
        }
        if options["label_column"]:
            kwargs["label_column"] = options["label_column"]
        grass.run_command("v.to.rast", quiet=True, **kwargs)
        refname = options["vector_reference"] + " with column " + options[
            "column"]
        # reset region
        grass.run_command("g.region", region=savedregion, quiet=True)
        # remove region
        grass.run_command("g.remove",
                          flags="f",
                          type="region",
                          name=savedregion,
                          quiet=True)
    else:
        if not descriptionflag:
            grass.fatal(
                "Either <raster_reference> or <vector_reference> and <column> must be indicated"
            )
    return reference, refname
Ejemplo n.º 3
0
def fill_band(bandmap, tilemask):
    '''Function to fill null pixels with interpolated values'''

    temporary_band = gscript.tempname(20)
    temporary_band2 = gscript.tempname(20)
    gscript.run_command('r.fill.stats',
                        flags='k',
                        input_=bandmap,
                        output=temporary_band,
                        distance=1,
                        cells=2,
                        overwrite=True,
                        quiet=QUIET)

    null_test = gscript.read_command('r.stats',
                                     flags='N',
                                     input_=[tilemask,temporary_band],
                                     quiet=QUIET).splitlines()

    while '1 *' in null_test:
        gscript.run_command('r.fill.stats',
                            flags='k',
                            input_=temporary_band,
                            output=temporary_band2,
                            distance=1,
                            cells=2,
                            overwrite=True,
                            quiet=QUIET)

        gscript.run_command('g.rename',
                            raster=[temporary_band2, temporary_band],
                            overwrite=True,
                            quiet=QUIET)

        null_test = gscript.read_command('r.stats',
                                         flags='N',
                                         input_=[tilemask,temporary_band],
                                         quiet=QUIET).splitlines()

    filled_band = "%s_filled" % bandmap
    mapcalc_expression = "%s = round(%s)" % (filled_band, temporary_band)
    gscript.run_command('r.mapcalc',
                        expression=mapcalc_expression,
                        quiet=QUIET)


    gscript.run_command('g.remove',
                        type='raster',
                        name=temporary_band,
                        flags='f',
                        quiet=QUIET)

    return filled_band
import grass.script as grass
from grass.pygrass.vector import VectorTopo
from grass.pygrass.vector.basic import Bbox
from grass.pygrass.raster.history import History
from grass.pygrass.vector.geometry import Centroid
from grass.pygrass.vector.geometry import Point
from grass.pygrass.vector.geometry import Line
from osgeo import ogr

# check if GRASS is running or not
if "GISBASE" not in os.environ:
    sys.exit("You must be in GRASS GIS to run this program")

# Define additional variables
# global TMP_PREFIX
TMP_PREFIX = grass.tempname(12)


def cleanup():
    """Remove temporary data
    """
    grass.del_temp_region()
    tmp_maps = grass.read_command("g.list",
                                  type=['vector', 'raster'],
                                  pattern='{}*'.format(TMP_PREFIX),
                                  separator=',')

    if tmp_maps:
        grass.run_command("g.remove",
                          type=['vector', 'raster'],
                          pattern='{}*'.format(TMP_PREFIX),
Ejemplo n.º 5
0
def main():
    """Do the main work"""
    # Define static variables
    global tmpname
    tmpname = gscript.tempname(12)

    # Define user input variables
    a_flag = flags["a"]
    elevation = options["elevation"]
    direction = options["direction"]
    slope_measure = options["slope_measure"]
    outputs = options["output"].split(",")
    dir_format = options["dir_type"]

    try:
        steps = list(map(int, options["steps"].split(",")))
    except:
        gscript.fatal(_("Not all steps given as integer."))

    n_steps = max(steps)

    abs = "abs" if a_flag else ""

    dir_values = gscript.parse_command("r.info", map=direction, flags="r")

    dir_type = check_directions(dir_format, float(dir_values["max"]))

    # Ceck if number of requested steps and outputs match
    if len(outputs) != len(steps):
        gscript.fatal(_("Number of steps and number of output maps differ"))

    # Define static variables
    kwargs_even = {
        "dir": direction,
        "elev_in": "{}_elev_even".format(tmpname),
        "elev_out": "{}_elev_odd".format(tmpname),
    }
    kwargs_odd = {
        "dir": direction,
        "elev_in": "{}_elev_odd".format(tmpname),
        "elev_out": "{}_elev_even".format(tmpname),
    }

    if slope_measure != "difference":
        kwargs_even["dist_in"] = "{}_dist_even".format(tmpname)
        kwargs_even["dist_out"] = "{}_dist_odd".format(tmpname)
        kwargs_even["dist_sum_in"] = "{}_dist_sum_even".format(tmpname)
        kwargs_even["dist_sum_out"] = "{}_dist_sum_odd".format(tmpname)
        kwargs_odd["dist_in"] = "{}_dist_odd".format(tmpname)
        kwargs_odd["dist_out"] = "{}_dist_even".format(tmpname)
        kwargs_odd["dist_sum_in"] = "{}_dist_sum_odd".format(tmpname)
        kwargs_odd["dist_sum_out"] = "{}_dist_sum_even".format(tmpname)

    dir_format_dict = {
        "degree_45": [1, 2, 3, 4, 5, 6, 7],
        "degree": [45, 90, 135, 180, 225, 270, 315],
        "bitmask": [1, 8, 7, 6, 5, 4, 3],
    }

    slope_measure_dict = {
        "difference": """\n{gradient}={abs}({elev}-{elev_in})""",
        "percent": """\n{gradient}={abs}({elev}-{elev_in})/{dist}""",
        "percent_int": """\n{gradient}=round(({abs}(({elev}-{elev_in}))/{dist})*10000.0)""",
        "degree": """\n{gradient}=atan({abs}({elev}-{elev_in})/{dist})""",
        "degree_int": """\n{gradient}=round(atan({abs}({elev}-{elev_in})/{dist})*100.0)""",
    }

    dirs = dir_format_dict[dir_type]

    expression_template = """{{elev_out}}=\
if({{dir}} == {0}, if(isnull({{elev_in}}[-1,1]),{{elev_in}},{{elev_in}}[-1,1]), \
if({{dir}} == {1}, if(isnull({{elev_in}}[-1,0]),{{elev_in}},{{elev_in}}[-1,0]), \
if({{dir}} == {2}, if(isnull({{elev_in}}[-1,-1]),{{elev_in}},{{elev_in}}[-1,-1]), \
if({{dir}} == {3}, if(isnull({{elev_in}}[0,-1]),{{elev_in}},{{elev_in}}[0,-1]), \
if({{dir}} == {4}, if(isnull({{elev_in}}[1,-1]),{{elev_in}},{{elev_in}}[1,-1]), \
if({{dir}} == {5}, if(isnull({{elev_in}}[1,0]),{{elev_in}},{{elev_in}}[1,0]), \
if({{dir}} == {6}, if(isnull({{elev_in}}[1,1]),{{elev_in}},{{elev_in}}[1,1]), \
if(isnull({{elev_in}}[0,1]),{{elev_in}},{{elev_in}}[0,1]))))))))""".format(
        *dirs
    )

    kwargs = {
        "dir": direction,
        "elev_in": elevation,
        "elev_out": "{}_elev_even".format(tmpname),
    }

    if slope_measure != "difference":
        expression_template += """\n{{dist_out}}=\
if({{dir}} == {0}, if(isnull({{dist_in}}[-1,1]),{{dist_in}},{{dist_in}}[-1,1]), \
if({{dir}} == {1}, if(isnull({{dist_in}}[-1,0]),{{dist_in}},{{dist_in}}[-1,0]), \
if({{dir}} == {2}, if(isnull({{dist_in}}[-1,-1]),{{dist_in}},{{dist_in}}[-1,-1]), \
if({{dir}} == {3}, if(isnull({{dist_in}}[0,-1]),{{dist_in}},{{dist_in}}[0,-1]), \
if({{dir}} == {4}, if(isnull({{dist_in}}[1,-1]),{{dist_in}},{{dist_in}}[1,-1]), \
if({{dir}} == {5}, if(isnull({{dist_in}}[1,0]),{{dist_in}},{{dist_in}}[1,0]), \
if({{dir}} == {6}, if(isnull({{dist_in}}[1,1]),{{dist_in}},{{dist_in}}[1,1]), \
if(isnull({{dist_in}}[0,1]),{{dist_in}},{{dist_in}}[0,1]))))))))
{{dist_sum_out}}={{dist_sum_in}}+{{dist_in}}""".format(
            *dirs
        )

        kwargs["dist_in"] = "{}_dist_odd".format(tmpname)
        kwargs["dist_out"] = "{}_dist_even".format(tmpname)
        kwargs["dist_sum_in"] = "{}_dist_sum_odd".format(tmpname)
        kwargs["dist_sum_out"] = "{}_dist_sum_even".format(tmpname)

        # Start processing
        curent_region = gscript.region()

        gscript.run_command(
            "r.mapcalc",
            overwrite=True,
            quiet=True,
            expression="""{dist_in}=\
if({dir} == {NE} || {dir} == {NW} || {dir} == {SW}\
|| {dir} == {SE}, sqrt({ewres}^2+{nsres}^2), \
if({dir} == {N} || {dir} == {S},{nsres},{ewres}))
{dist_sum_in}=0""".format(
                NE=dirs[0],
                NW=dirs[2],
                SW=dirs[4],
                SE=dirs[6],
                N=dirs[1],
                S=dirs[5],
                nsres=curent_region["nsres"],
                ewres=curent_region["ewres"],
                dir=direction,
                dist_in=kwargs["dist_in"],
                dist_sum_in=kwargs["dist_sum_in"],
            ),
        )

    for x in range(max(steps) + 1):
        mc_expression = expression_template.format(**kwargs)

        if x in steps:
            idx = steps.index(x)
            # Compile expression for r.mapcalc
            result_expression = slope_measure_dict[slope_measure]
            # Results are computed for output from previous step
            if slope_measure != "difference":
                result_kwargs = {
                    "elev_in": kwargs["elev_in"],
                    "elev": elevation,
                    "dist": kwargs["dist_sum_in"],
                    "abs": abs,
                    "gradient": outputs[idx],
                }
            else:
                result_kwargs = {
                    "elev_in": kwargs["elev_in"],
                    "elev": elevation,
                    "abs": abs,
                    "gradient": outputs[idx],
                }

            result_expression = result_expression.format(**result_kwargs)

            if x == max(steps):
                mc_expression = result_expression.lstrip("\n")
            else:
                mc_expression += result_expression

        gscript.run_command(
            "r.mapcalc", overwrite=True, quiet=True, expression=mc_expression
        )

        if x in steps:
            gscript.raster.raster_history(outputs[idx])

        # Set variables for next iteration
        # Use even and odd numbers for iterative re-naming
        if x % 2 == 0:
            # Even
            kwargs = kwargs_even
        else:
            # Odd
            kwargs = kwargs_odd

        gscript.percent(x, max(steps), 1)
Ejemplo n.º 6
0
def main():
    """Do the main work"""
    # Define static variables
    global tmpname
    tmpname = gscript.tempname(12)

    # Define user input variables
    a_flag = flags['a']
    elevation = options['elevation']
    direction = options['direction']
    slope_measure = options['slope_measure']
    outputs = options['output'].split(',')
    dir_format = options['dir_type']

    try:
        steps = list(map(int, options['steps'].split(',')))
    except:
        gscript.fatal(_('Not all steps given as integer.'))

    n_steps = max(steps)

    abs = 'abs' if a_flag else ''

    dir_values = gscript.parse_command('r.info', map=direction, flags='r')

    dir_type = check_directions(dir_format, float(dir_values['max']))

    # Ceck if number of requested steps and outputs match
    if len(outputs) != len(steps):
        gscript.fatal(_("Number of steps and number of output maps differ"))

    # Define static variables
    kwargs_even = {
        'dir': direction,
        'elev_in': '{}_elev_even'.format(tmpname),
        'elev_out': '{}_elev_odd'.format(tmpname)
    }
    kwargs_odd = {
        'dir': direction,
        'elev_in': '{}_elev_odd'.format(tmpname),
        'elev_out': '{}_elev_even'.format(tmpname)
    }

    if slope_measure != 'difference':
        kwargs_even['dist_in'] = '{}_dist_even'.format(tmpname)
        kwargs_even['dist_out'] = '{}_dist_odd'.format(tmpname)
        kwargs_even['dist_sum_in'] = '{}_dist_sum_even'.format(tmpname)
        kwargs_even['dist_sum_out'] = '{}_dist_sum_odd'.format(tmpname)
        kwargs_odd['dist_in'] = '{}_dist_odd'.format(tmpname)
        kwargs_odd['dist_out'] = '{}_dist_even'.format(tmpname)
        kwargs_odd['dist_sum_in'] = '{}_dist_sum_odd'.format(tmpname)
        kwargs_odd['dist_sum_out'] = '{}_dist_sum_even'.format(tmpname)

    dir_format_dict = {
        'degree_45': [1, 2, 3, 4, 5, 6, 7],
        'degree': [45, 90, 135, 180, 225, 270, 315],
        'bitmask': [1, 8, 7, 6, 5, 4, 3]
    }

    slope_measure_dict = {
        'difference':
        """\n{gradient}={abs}({elev}-{elev_in})""",
        'percent':
        """\n{gradient}={abs}({elev}-{elev_in})/{dist}""",
        'percent_int':
        """\n{gradient}=round(({abs}(({elev}-{elev_in}))/{dist})*10000.0)""",
        'degree':
        """\n{gradient}=atan({abs}({elev}-{elev_in})/{dist})""",
        'degree_int':
        """\n{gradient}=round(atan({abs}({elev}-{elev_in})/{dist})*100.0)"""
    }

    dirs = dir_format_dict[dir_type]

    expression_template = """{{elev_out}}=\
if({{dir}} == {0}, if(isnull({{elev_in}}[-1,1]),{{elev_in}},{{elev_in}}[-1,1]), \
if({{dir}} == {1}, if(isnull({{elev_in}}[-1,0]),{{elev_in}},{{elev_in}}[-1,0]), \
if({{dir}} == {2}, if(isnull({{elev_in}}[-1,-1]),{{elev_in}},{{elev_in}}[-1,-1]), \
if({{dir}} == {3}, if(isnull({{elev_in}}[0,-1]),{{elev_in}},{{elev_in}}[0,-1]), \
if({{dir}} == {4}, if(isnull({{elev_in}}[1,-1]),{{elev_in}},{{elev_in}}[1,-1]), \
if({{dir}} == {5}, if(isnull({{elev_in}}[1,0]),{{elev_in}},{{elev_in}}[1,0]), \
if({{dir}} == {6}, if(isnull({{elev_in}}[1,1]),{{elev_in}},{{elev_in}}[1,1]), \
if(isnull({{elev_in}}[0,1]),{{elev_in}},{{elev_in}}[0,1]))))))))""".format(
        *dirs)

    kwargs = {
        'dir': direction,
        'elev_in': elevation,
        'elev_out': '{}_elev_even'.format(tmpname)
    }

    if slope_measure != 'difference':
        expression_template += """\n{{dist_out}}=\
if({{dir}} == {0}, if(isnull({{dist_in}}[-1,1]),{{dist_in}},{{dist_in}}[-1,1]), \
if({{dir}} == {1}, if(isnull({{dist_in}}[-1,0]),{{dist_in}},{{dist_in}}[-1,0]), \
if({{dir}} == {2}, if(isnull({{dist_in}}[-1,-1]),{{dist_in}},{{dist_in}}[-1,-1]), \
if({{dir}} == {3}, if(isnull({{dist_in}}[0,-1]),{{dist_in}},{{dist_in}}[0,-1]), \
if({{dir}} == {4}, if(isnull({{dist_in}}[1,-1]),{{dist_in}},{{dist_in}}[1,-1]), \
if({{dir}} == {5}, if(isnull({{dist_in}}[1,0]),{{dist_in}},{{dist_in}}[1,0]), \
if({{dir}} == {6}, if(isnull({{dist_in}}[1,1]),{{dist_in}},{{dist_in}}[1,1]), \
if(isnull({{dist_in}}[0,1]),{{dist_in}},{{dist_in}}[0,1]))))))))
{{dist_sum_out}}={{dist_sum_in}}+{{dist_in}}""".format(*dirs)

        kwargs['dist_in'] = '{}_dist_odd'.format(tmpname)
        kwargs['dist_out'] = '{}_dist_even'.format(tmpname)
        kwargs['dist_sum_in'] = '{}_dist_sum_odd'.format(tmpname)
        kwargs['dist_sum_out'] = '{}_dist_sum_even'.format(tmpname)

        # Start processing
        curent_region = gscript.region()

        gscript.run_command('r.mapcalc',
                            overwrite=True,
                            quiet=True,
                            expression="""{dist_in}=\
if({dir} == {NE} || {dir} == {NW} || {dir} == {SW}\
|| {dir} == {SE}, sqrt({ewres}^2+{nsres}^2), \
if({dir} == {N} || {dir} == {S},{nsres},{ewres}))
{dist_sum_in}=0""".format(NE=dirs[0],
                          NW=dirs[2],
                          SW=dirs[4],
                          SE=dirs[6],
                          N=dirs[1],
                          S=dirs[5],
                          nsres=curent_region['nsres'],
                          ewres=curent_region['ewres'],
                          dir=direction,
                          dist_in=kwargs['dist_in'],
                          dist_sum_in=kwargs['dist_sum_in']))

    for x in range(max(steps) + 1):
        mc_expression = expression_template.format(**kwargs)

        if x in steps:
            idx = steps.index(x)
            # Compile expression for r.mapcalc
            result_expression = slope_measure_dict[slope_measure]
            # Results are computed for output from previous step
            if slope_measure != 'difference':
                result_kwargs = {
                    'elev_in': kwargs['elev_in'],
                    'elev': elevation,
                    'dist': kwargs['dist_sum_in'],
                    'abs': abs,
                    'gradient': outputs[idx]
                }
            else:
                result_kwargs = {
                    'elev_in': kwargs['elev_in'],
                    'elev': elevation,
                    'abs': abs,
                    'gradient': outputs[idx]
                }

            result_expression = result_expression.format(**result_kwargs)

            if x == max(steps):
                mc_expression = result_expression.lstrip('\n')
            else:
                mc_expression += result_expression

        gscript.run_command('r.mapcalc',
                            overwrite=True,
                            quiet=True,
                            expression=mc_expression)

        if x in steps:
            gscript.raster.raster_history(outputs[idx])

        # Set variables for next iteration
        # Use even and odd numbers for iterative re-naming
        if x % 2 == 0:
            # Even
            kwargs = kwargs_even
        else:
            # Odd
            kwargs = kwargs_odd

        gscript.percent(x, max(steps), 1)
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
def tmpname():
    """Generate a tmp name and stores it in the global list."""
    tmpf = gs.tempname(12)
    clean_layers.append(tmpf)
    return tmpf
Ejemplo n.º 9
0
import itertools

from grass.pygrass.gis import Mapset
from grass.pygrass.raster import RasterRow
from grass.pygrass.raster import raster2numpy
from grass.pygrass.raster import numpy2raster

from grass.pygrass.gis.region import Region
from grass.pygrass.vector.basic import Bbox

import grass.script as grass
from grass.script import utils as grassutils

# Declare global variables
# random name of binary viewshed
TEMPNAME = grass.tempname(12)


def cleanup():
    """Remove raster and vector maps stored in a list"""
    grass.run_command(
        "g.remove",
        flags="f",
        type="raster,vector",
        pattern="{}_*".format(TEMPNAME),
        quiet=True,
        stderr=subprocess.PIPE,
    )

    # Reset mask if user MASK was present
    if (RasterRow("MASK",
Ejemplo n.º 10
0
# %rules
# % required: alias_input,env_maps
# % exclusive: alias_input,alias_output
# % requires: alias_output,alias_names
# % requires: species_names,species_masks
# % requires: species_output,species_masks
# %end

import atexit
import os

import grass.script as gscript
from grass.pygrass.gis import Mapset
from grass.pygrass.raster import RasterRow

TMP_NAME = gscript.tempname(12)


def cleanup():
    """Restore old mask if it existed"""
    if RasterRow("{}_MASK".format(TMP_NAME), Mapset().name).exist():
        gscript.verbose("Restoring old mask...")
        if RasterRow("MASK", Mapset().name).exist():
            gscript.run_command("r.mask", flags="r")
        gscript.run_command(
            "g.rename", rast="{}_MASK,MASK".format(TMP_NAME), quiet=True
        )
    if RasterRow("MASK", Mapset().name).exist():
        gscript.run_command("r.mask", flags="r")

Ejemplo n.º 11
0
class TestFunctions(TestCase):
    """The main (and only) test case for the r.viewshed.exposure module"""

    tempname = gs.tempname(12)

    # Raster maps used as inputs
    source_roads = "roadsmajor@PERMANENT"
    source_lakes = "lakes@PERMANENT"
    source_points = "geodetic_swwake_pts@PERMANENT"
    dsm = "elevation@PERMANENT"

    functions = [
        "Binary",
        "Fuzzy_viewshed",
        "Distance_decay",
        "Solid_angle",
        "Visual_magnitude",
    ]

    r_viewshed = SimpleModule(
        "r.viewshed.exposure",
        flags="cr",
        input=dsm,
        source=source_roads,
        observer_elevation=1.5,
        range=100,
        b1_distance=10,
        sample_density=5,
        seed=50,
        memory=5000,
        nprocs=10,
        quiet=True,
        overwrite=True,
    )

    test_results_stats = {
        "test_roads_B": {
            "n": 120880,
            "null_cells": 1904120,
            "cells": 2025000,
            "min": 0,
            "max": 15,
            "range": 15,
            "mean": 1.62403,
            "mean_of_abs": 1.62403,
            "stddev": 1.93013,
            "variance": 3.72542,
            "coeff_var": 118.848259976884,
            "sum": 196313,
        },
        "test_roads_F": {
            "n": 120880,
            "null_cells": 1904120,
            "cells": 2025000,
            "min": 0,
            "max": 11.3565,
            "range": 11.3565,
            "mean": 1.20334,
            "mean_of_abs": 1.20334,
            "stddev": 1.47689,
            "variance": 2.18121,
            "coeff_var": 122.732631198116,
            "sum": 145459.99071890,
        },
        "test_roads_D": {
            "n": 120880,
            "null_cells": 1904120,
            "cells": 2025000,
            "min": 0,
            "max": 3.86,
            "range": 3.86,
            "mean": 0.118786,
            "mean_of_abs": 0.118786,
            "stddev": 0.275875,
            "variance": 0.076107,
            "coeff_var": 232.246,
            "sum": 14358.8130874699,
        },
        "test_roads_S": {
            "n": 120749,
            "null_cells": 1904251,
            "cells": 2025000,
            "min": 0,
            "max": 3.00867,
            "range": 3.00867,
            "mean": 0.0232121,
            "mean_of_abs": 0.0232121,
            "stddev": 0.202763,
            "variance": 0.0411129,
            "coeff_var": 873.523497082485,
            "sum": 2802.8384487502,
        },
        "test_roads_V": {
            "n": 120749,
            "null_cells": 1904251,
            "cells": 2025000,
            "min": 0,
            "max": 45.2416,
            "range": 45.2416,
            "mean": 0.34082,
            "mean_of_abs": 0.34082,
            "stddev": 3.80045,
            "variance": 14.4434,
            "coeff_var": 1115.09106861343,
            "sum": 41153.6541857501,
        },
        "test_lakes": {
            "n": 75396,
            "null_cells": 1949604,
            "cells": 2025000,
            "min": 0,
            "max": 4.61498,
            "range": 4.61498,
            "mean": 0.422226,
            "mean_of_abs": 0.422226,
            "stddev": 0.555438,
            "variance": 0.308511,
            "coeff_var": 131.549853569661,
            "sum": 31834.1479829689,
        },
        "test_points": {
            "n": 97340,
            "null_cells": 1927660,
            "cells": 2025000,
            "min": 0,
            "max": 11.8462,
            "range": 11.8462,
            "mean": 0.0432476,
            "mean_of_abs": 0.0432476,
            "stddev": 0.144737,
            "variance": 0.0209488,
            "coeff_var": 334.675522436311,
            "sum": 4209.66482665949,
        },
    }

    @classmethod
    def setUpClass(cls):
        """Setup temp region."""

        # Save current region to temporary file
        gs.use_temp_region()
        gs.run_command("g.region", raster=cls.dsm, align=cls.dsm)

    @classmethod
    def tearDownClass(cls):
        """Reset original region and remove the temporary region"""
        gs.del_temp_region()

    def tearDown(self):
        """Remove the output created from the module
        This is executed after each test function run. If we had
        something to set up before each test function run, we would use setUp()
        function.
        Since we remove the raster map after running each test function,
        we can reuse the same name for all the test functions.
        """
        self.runModule("g.remove", flags="f", type="raster", pattern="test_2*")

    def test_roads(self):
        """Test exposure to roads using all viewshed parametrisation functions"""

        # Use the input DSM to set computational region
        gs.run_command("g.region", raster=self.dsm, align=self.dsm)

        for function in self.functions:

            # Output dataset
            output = "test_roads_{}".format(function[0])
            self.r_viewshed.outputs.output = output

            # Input datasets
            self.r_viewshed.inputs.input = self.dsm
            self.r_viewshed.inputs.source = self.source_roads
            self.r_viewshed.inputs.function = function
            self.r_viewshed.inputs.sampling_points = None

            # # Print the command
            # print(self.r_viewshed.get_bash())

            # Check that the module runs
            self.assertModule(self.r_viewshed)

            # Check to see if output is in mapset
            self.assertRasterExists(output, msg="Output was not created")

            # Here we need to check if univariate raster statistics match the expected result
            self.assertRasterFitsUnivar(
                raster=output,
                reference=self.test_results_stats[output],
                precision=1e-4,
            )

    def test_lakes(self):
        """Test exposure to lakes."""

        # Use the input DSM to set computational region
        gs.run_command("g.region", raster=self.dsm, align=self.dsm)

        function = "Distance_decay"

        # Output dataset
        output = "test_lakes"
        self.r_viewshed.outputs.output = output

        # Input dataset
        self.r_viewshed.inputs.input = self.dsm
        self.r_viewshed.inputs.source = self.source_lakes
        self.r_viewshed.inputs.function = function

        # # Print the command
        # print(self.r_viewshed.get_bash())

        # Check that the module runs
        self.assertModule(self.r_viewshed)

        # Check to see if output is in mapset
        self.assertRasterExists(output, msg="Output was not created")

        # Here we need to check if univariate raster statistics match the expected result
        self.assertRasterFitsUnivar(
            raster=output,
            reference=self.test_results_stats[output],
            precision=1e-5,
        )

    def test_points(self):
        """Test exposure from points"""

        # Use of of the input dsm to set computational region
        gs.run_command("g.region", raster=self.dsm, align=self.dsm)

        function = "Distance_decay"

        # Output datasets
        output = "test_points"
        self.r_viewshed.outputs.output = output

        # Input datasets
        self.r_viewshed.inputs.input = self.dsm
        self.r_viewshed.inputs.source = None
        self.r_viewshed.inputs.sampling_points = self.source_points
        self.r_viewshed.inputs.function = function

        # # Print command
        # print(self.r_viewshed.get_bash())

        # Check that the module runs
        self.assertModule(self.r_viewshed)

        # Check to see if output is in mapset
        self.assertRasterExists(output, msg="Output was not created")

        # Here we need to check if univariate raster statistics match the expected result
        self.assertRasterFitsUnivar(
            raster=output,
            reference=self.test_results_stats[output],
            precision=1e-4,
        )