Esempio n. 1
0
def main():
    magnitude = options['magnitude']
    direction = options['direction']
    divergence = options['output']
    global TMP, CLEANUP

    tmp_name = 'tmp_divergence_' + str(os.getpid())
    qsx = tmp_name + "qsx"
    qsy = tmp_name + "qsy"
    qsx_dx = tmp_name + "qsx_dx"
    qsy_dy = tmp_name + "qsy_dy"
    TMP.extend([qsx, qsy, qsx_dx, qsy_dy])

    # checks if there are already some maps
    old_maps = temp_maps_exist()
    if old_maps:
        if not gcore.overwrite():
            CLEANUP = False
            gcore.fatal(
                _("You have to first check overwrite flag or remove"
                  " the following maps:\n"
                  "names}").format(names=','.join(old_maps)))
        else:
            gcore.warning(
                _("The following maps will be overwritten: {names}").format(
                    names=','.join(old_maps)))
    try:
        grast.mapcalc(exp="{qsx}={mag} * cos({direct})".format(
            qsx=qsx, mag=magnitude, direct=direction))
        grast.mapcalc(exp="{qsy}={mag} * sin({direct})".format(
            qsy=qsy, mag=magnitude, direct=direction))
        gcore.run_command('r.slope.aspect', elevation=qsx, dx=qsx_dx)
        gcore.run_command('r.slope.aspect', elevation=qsy, dy=qsy_dy)
        grast.mapcalc(exp="{div}={qsx_dx} + {qsy_dy}".format(
            div=divergence, qsx_dx=qsx_dx, qsy_dy=qsy_dy))
    except CalledModuleError:
        gcore.fatal(
            _("r.divergence failed, check errors above. Please report this problem to developers."
              ))
        return 1

    grast.raster_history(divergence)
    return 0
Esempio n. 2
0
def main():
    elev = options['input']
    output = options['output']
    n_dir = int(options['ndir'])
    global TMP_NAME, CLEANUP
    if options['basename']:
        TMP_NAME = options['basename']
        CLEANUP = False
    colorized_output = options['colorized_output']
    colorize_color = options['color_table']
    if colorized_output:
        color_raster_tmp = TMP_NAME + "_color_raster"
    else:
        color_raster_tmp = None
    color_raster_type = options['color_source']
    color_input = options['color_input']
    if color_raster_type == 'color_input' and not color_input:
        gcore.fatal(_("Provide raster name in color_input option"))
    if color_raster_type != 'color_input' and color_input:
        gcore.fatal(
            _("The option color_input is not needed"
              " when not using it as source for color"))
    # this would be needed only when no value would allowed
    if not color_raster_type and color_input:
        color_raster_type = 'color_input'  # enable for convenience
    if color_raster_type == 'aspect' \
            and colorize_color \
            and colorize_color not in ['default', 'aspectcolr']:
        gcore.warning(
            _("Using possibly inappropriate color table <{}>"
              " for aspect".format(colorize_color)))

    horizon_step = 360. / n_dir
    msgr = get_msgr()

    # checks if there are already some maps
    old_maps = _get_horizon_maps()
    if old_maps:
        if not gcore.overwrite():
            CLEANUP = False
            msgr.fatal(
                _("You have to first check overwrite flag or remove"
                  " the following maps:\n"
                  "{names}").format(names=','.join(old_maps)))
        else:
            msgr.warning(
                _("The following maps will be overwritten: {names}").format(
                    names=','.join(old_maps)))
    if not gcore.overwrite() and color_raster_tmp:
        check_map_name(color_raster_tmp)
    try:
        params = {}
        if options['maxdistance']:
            params['maxdistance'] = options['maxdistance']
        gcore.run_command('r.horizon',
                          elevation=elev,
                          step=horizon_step,
                          output=TMP_NAME,
                          flags='d',
                          **params)

        new_maps = _get_horizon_maps()
        if flags['o']:
            msgr.message(_("Computing openness ..."))
            expr = '{out} = 1 - (sin({first}) '.format(first=new_maps[0],
                                                       out=output)
            for horizon in new_maps[1:]:
                expr += '+ sin({name}) '.format(name=horizon)
            expr += ") / {n}.".format(n=len(new_maps))
        else:
            msgr.message(_("Computing skyview factor ..."))
            expr = '{out} = 1 - (sin( if({first} < 0, 0, {first}) ) '.format(
                first=new_maps[0], out=output)
            for horizon in new_maps[1:]:
                expr += '+ sin( if({name} < 0, 0, {name}) ) '.format(
                    name=horizon)
            expr += ") / {n}.".format(n=len(new_maps))

        grast.mapcalc(exp=expr)
        gcore.run_command('r.colors', map=output, color='grey')
    except CalledModuleError:
        msgr.fatal(
            _("r.horizon failed to compute horizon elevation "
              "angle maps. Please report this problem to developers."))
        return 1
    if colorized_output:
        if color_raster_type == 'slope':
            gcore.run_command('r.slope.aspect',
                              elevation=elev,
                              slope=color_raster_tmp)
        elif color_raster_type == 'aspect':
            gcore.run_command('r.slope.aspect',
                              elevation=elev,
                              aspect=color_raster_tmp)
        elif color_raster_type == 'dxy':
            gcore.run_command('r.slope.aspect',
                              elevation=elev,
                              dxy=color_raster_tmp)
        elif color_raster_type == 'color_input':
            color_raster_tmp = color_input
        else:
            color_raster_tmp = elev
        # don't modify user's color table for inputs
        if colorize_color \
                and color_raster_type not in ['input', 'color_input']:
            rcolors_flags = ''
            if flags['n']:
                rcolors_flags += 'n'
            gcore.run_command('r.colors',
                              map=color_raster_tmp,
                              color=colorize_color,
                              flags=rcolors_flags)
        gcore.run_command('r.shade',
                          shade=output,
                          color=color_raster_tmp,
                          output=colorized_output)
        grast.raster_history(colorized_output)
    grast.raster_history(output)
    return 0
def main():
    size = int(options['size'])
    gamma = scale = None
    if options['gamma']:
        gamma = float(options['gamma'])
    if options['scaling_factor']:
        scale = float(options['scaling_factor'])
    input_dev = options['input']
    output = options['output']
    method = options['method']

    if method in ('gravity', 'kernel') and (gamma is None or scale is None):
        gcore.fatal(
            _("Methods gravity and kernel require options scaling_factor and gamma"
              ))

    temp_map = 'tmp_futures_devPressure_' + str(os.getpid()) + '_copy'
    temp_map_out = 'tmp_futures_devPressure_' + str(os.getpid()) + '_out'
    temp_map_nulls = 'tmp_futures_devPressure_' + str(os.getpid()) + '_nulls'
    global TMP, TMPFILE
    if flags['n']:
        gcore.message(_("Preparing data..."))
        region = gcore.region()
        gcore.use_temp_region()
        gcore.run_command('g.region',
                          n=region['n'] + size * region['nsres'],
                          s=region['s'] - size * region['nsres'],
                          e=region['e'] + size * region['ewres'],
                          w=region['w'] - size * region['ewres'])
        TMP.append(temp_map)
        TMP.append(temp_map_nulls)
        TMP.append(temp_map_out)
        exp = "{temp_map_nulls} = if(isnull({inp}), 1, null())".format(
            temp_map_nulls=temp_map_nulls, inp=input_dev)
        grast.mapcalc(exp=exp)
        grast.mapcalc(exp="{temp} = if(isnull({inp}), 0, {inp})".format(
            temp=temp_map, inp=input_dev))
        rmfilter_inp = temp_map
        rmfilter_out = temp_map_out
    else:
        rmfilter_inp = input_dev
        rmfilter_out = output

    matrix = distance_matrix(size)
    if method == 'occurrence':
        matrix[matrix > 0] = 1
    elif method == 'gravity':
        with np.errstate(divide='ignore'):
            denom = np.power(matrix, gamma)
            matrix = scale / denom
            matrix[denom == 0] = 0
    else:
        matrix_ = scale * np.exp(-2 * matrix / gamma)
        matrix = np.where(matrix > 0, matrix_, 0)

    path = gcore.tempfile()
    global TMPFILE
    TMPFILE = path

    with open(path, 'w') as f:
        f.write(write_filter(matrix))
    gcore.message(_("Running development pressure filter..."))
    gcore.run_command('r.mfilter',
                      input=rmfilter_inp,
                      output=rmfilter_out,
                      filter=path)

    if flags['n']:
        gcore.run_command(
            'g.region',
            n=region['n'],
            s=region['s'],
            e=region['e'],
            w=region['w'],
        )
        grast.mapcalc(
            exp="{out} = if(isnull({temp_null}), {rmfilter_out}, null())".
            format(temp_null=temp_map_nulls,
                   rmfilter_out=rmfilter_out,
                   out=output))
        gcore.del_temp_region()

    grast.raster_history(output)
Esempio n. 4
0
def main():
    """Do the main work"""
    lambdas_file = options["lambdas_file"]
    alias_file = options["alias_file"]

    if not options["ndigits"].isdigit():
        gscript.fatal(_("The ndigits option needs to be given as integer."))

    ndigits = int(options["ndigits"])

    if ndigits > 5 or ndigits < 0:
        gscript.warning(
            _("Valid range for ndigits is 0 to 5. \
        Setting to closest bound."))

    ndigits = max(0, min(ndigits, 5))

    raw = options["raw"]

    logistic = options["logistic"]

    if int(options["nprocs"]) > 1:
        if not gscript.find_program("r.mapcalc.tiled"):
            gscript.fatal(
                _("Cannot find r.mapcalc.tiled for parallel processing.\n"
                  "Please install it with 'g.extension r.mapcalc.tiled'"))
        rmapcalc = partial(
            tiled_mapcalc,
            width=options["width"],
            height=options["height"],
            nprocs=options["nprocs"],
        )
    else:
        rmapcalc = mapcalc

    # Check if input file exists and is readable
    if not os.access(lambdas_file, os.R_OK):
        gscript.fatal(
            _("MaxEnt lambdas-file could not be found or is not readable."))

    # Parse alias_file if provided
    alias_dict = parse_alias(alias_file)

    ###Parse lambdas-file and translate it to a mapcalculator expression
    ###Get variables linearPredictorNormalizer, densityNormalizer and entropy from lambdas-file
    with open(lambdas_file, "r") as l_f:
        mc_expression_parts = []
        for lrow in l_f:
            if (not lrow.strip() or lrow.startswith("numBackgroundPoints")
                    or "," not in lrow):
                continue
            lrow = lrow.replace(" ", "").rstrip("\n")
            coeff = lrow.split(",")
            if lrow.startswith("linearPredictorNormalizer"):
                linear_predictor_normalizer = coeff[1]
            elif lrow.startswith("densityNormalizer"):
                density_normalizer = coeff[1]
            # elif lrow.startswith("numBackgroundPoints"):
            # numBackgroundPoints = coeff[1]
            # continue
            elif lrow.startswith("entropy"):
                entropy = coeff[1]
            else:
                lrow = parse_lambdas_row(lrow, coeff, alias_dict, flags["c"])
                isnull = "|".join(
                    ["isnull({})".format(rmap) for rmap in lrow[0]])
                mc_expression_parts.append(
                    lrow[1] if flags["n"] else "if({0},0,{1})".
                    format(isnull, lrow[1]))

    # Compile mapcalc-expression
    mc_expression_raw = "exp((("
    mc_expression_raw += "+".join(mc_expression_parts)
    mc_expression_raw += ")-{0}))/{1}".format(linear_predictor_normalizer,
                                              density_normalizer)

    ###Compute raw output map by sending expression saved in file temporary file to r.mapcalc
    if raw:
        raw_expr = "{out_map}={expr}".format(out_map=raw,
                                             expr=mc_expression_raw)
        if flags["p"]:
            print(raw_expr)
            return 0
        rmapcalc(raw_expr)
        raster_history(raw, overwrite=True)

    ###Compute logistic output map if not suppressed
    if logistic:
        mc_expression_log = (
            "(({expr})*exp({entropy}))/(1.0+(({expr})*exp({entropy})))".format(
                expr=mc_expression_raw, entropy=entropy))
        if ndigits > 0:
            mc_expression_log = "round(({expr})*(10^{ndigits}))".format(
                expr=mc_expression_log, ndigits=ndigits)
        log_expr = "{out_map}={expr}".format(out_map=logistic,
                                             expr=mc_expression_log)
        if flags["p"]:
            print(log_expr)
            return 0
        rmapcalc(log_expr)
        if flags["N"]:
            gscript.run_command("r.null", map=logistic, setnull=0)
        raster_history(logistic, overwrite=True)
    return 0
def main():
    elev = options["input"]
    output = options["output"]
    n_dir = int(options["ndir"])
    notParallel = flags["p"]

    global TMP_NAME, CLEANUP

    if options["basename"]:
        TMP_NAME = options["basename"]
        CLEANUP = False

    colorized_output = options["colorized_output"]
    colorize_color = options["color_table"]

    if colorized_output:
        color_raster_tmp = TMP_NAME + "_color_raster"
    else:
        color_raster_tmp = None

    color_raster_type = options["color_source"]
    color_input = options["color_input"]

    if color_raster_type == "color_input" and not color_input:
        gcore.fatal(_("Provide raster name in color_input option"))

    if color_raster_type != "color_input" and color_input:
        gcore.fatal(
            _(
                "The option color_input is not needed"
                " when not using it as source for color"
            )
        )
    # this would be needed only when no value would allowed
    if not color_raster_type and color_input:
        color_raster_type = "color_input"  # enable for convenience

    if (
        color_raster_type == "aspect"
        and colorize_color
        and colorize_color not in ["default", "aspectcolr"]
    ):
        gcore.warning(
            _(
                "Using possibly inappropriate color table <{}>"
                " for aspect".format(colorize_color)
            )
        )

    horizon_step = 360.0 / n_dir
    horizon_intervals = np.arange(0, 360, horizon_step)
    msgr = get_msgr()

    # checks if there are already some maps
    old_maps = _get_horizon_maps()

    if old_maps:
        if not gcore.overwrite():
            CLEANUP = False
            msgr.fatal(
                _(
                    "You have to first check overwrite flag or remove"
                    " the following maps:\n"
                    "{names}"
                ).format(names=",".join(old_maps))
            )
        else:
            msgr.warning(
                _("The following maps will be overwritten: {names}").format(
                    names=",".join(old_maps)
                )
            )

    if not gcore.overwrite() and color_raster_tmp:
        check_map_name(color_raster_tmp)

    try:
        if notParallel is False:
            if options["maxdistance"]:
                maxdistance = float(options["maxdistance"])
            else:
                maxdistance = None

            r_horizon = Module(
                "r.horizon",
                elevation=elev,
                maxdistance=maxdistance,
                flags="d",
                run_=False,
            )

            queue = ParallelModuleQueue(nprocs=int(options["processes"]))

            for d in horizon_intervals:
                r_horizon_prc = deepcopy(r_horizon)
                r_horizon_prc.inputs.direction = d
                r_horizon_prc.outputs.output = TMP_NAME
                queue.put(r_horizon_prc)

            queue.wait()

        else:
            params = {}
            if options["maxdistance"]:
                params["maxdistance"] = options["maxdistance"]

            gcore.run_command(
                "r.horizon",
                elevation=elev,
                step=horizon_step,
                output=TMP_NAME,
                flags="d",
                **params
            )

        new_maps = _get_horizon_maps()

        if flags["o"]:
            msgr.message(_("Computing openness ..."))
            expr = "{out} = 1 - (sin({first}) ".format(first=new_maps[0], out=output)
            for horizon in new_maps[1:]:
                expr += "+ sin({name}) ".format(name=horizon)
            expr += ") / {n}.".format(n=len(new_maps))
        else:
            msgr.message(_("Computing skyview factor ..."))
            expr = "{out} = 1 - (sin( if({first} < 0, 0, {first}) ) ".format(
                first=new_maps[0], out=output
            )
            for horizon in new_maps[1:]:
                expr += "+ sin( if({name} < 0, 0, {name}) ) ".format(name=horizon)
            expr += ") / {n}.".format(n=len(new_maps))
        
        grast.mapcalc(exp=expr)
        gcore.run_command("r.colors", map=output, color="grey")

    except CalledModuleError:
        msgr.fatal(
            _(
                "r.horizon failed to compute horizon elevation "
                "angle maps. Please report this problem to developers."
            )
        )
        return 1

    if colorized_output:
        if color_raster_type == "slope":
            gcore.run_command("r.slope.aspect", elevation=elev, slope=color_raster_tmp)
        elif color_raster_type == "aspect":
            gcore.run_command("r.slope.aspect", elevation=elev, aspect=color_raster_tmp)
        elif color_raster_type == "dxy":
            gcore.run_command("r.slope.aspect", elevation=elev, dxy=color_raster_tmp)
        elif color_raster_type == "color_input":
            color_raster_tmp = color_input
        else:
            color_raster_tmp = elev

        # don't modify user's color table for inputs
        if colorize_color and color_raster_type not in ["input", "color_input"]:
            rcolors_flags = ""

            if flags["n"]:
                rcolors_flags += "n"

            gcore.run_command(
                "r.colors",
                map=color_raster_tmp,
                color=colorize_color,
                flags=rcolors_flags,
            )

        gcore.run_command(
            "r.shade", shade=output, color=color_raster_tmp, output=colorized_output
        )
        grast.raster_history(colorized_output)

    grast.raster_history(output)

    return 0
Esempio n. 6
0
def main():
    size = int(options["size"])
    gamma = scale = None
    if options["gamma"]:
        gamma = float(options["gamma"])
    if options["scaling_factor"]:
        scale = float(options["scaling_factor"])
    input_dev = options["input"]
    output = options["output"]
    method = options["method"]

    if method in ("gravity", "kernel") and (gamma is None or scale is None):
        gcore.fatal(
            _("Methods gravity and kernel require options scaling_factor and gamma"
              ))

    temp_map = "tmp_futures_devPressure_" + str(os.getpid()) + "_copy"
    temp_map_out = "tmp_futures_devPressure_" + str(os.getpid()) + "_out"
    temp_map_nulls = "tmp_futures_devPressure_" + str(os.getpid()) + "_nulls"
    global TMP, TMPFILE
    if flags["n"]:
        gcore.message(_("Preparing data..."))
        region = gcore.region()
        gcore.use_temp_region()
        gcore.run_command(
            "g.region",
            n=region["n"] + size * region["nsres"],
            s=region["s"] - size * region["nsres"],
            e=region["e"] + size * region["ewres"],
            w=region["w"] - size * region["ewres"],
        )
        TMP.append(temp_map)
        TMP.append(temp_map_nulls)
        TMP.append(temp_map_out)
        exp = "{temp_map_nulls} = if(isnull({inp}), 1, null())".format(
            temp_map_nulls=temp_map_nulls, inp=input_dev)
        grast.mapcalc(exp=exp)
        grast.mapcalc(exp="{temp} = if(isnull({inp}), 0, {inp})".format(
            temp=temp_map, inp=input_dev))
        rmfilter_inp = temp_map
        rmfilter_out = temp_map_out
    else:
        rmfilter_inp = input_dev
        rmfilter_out = output

    matrix = distance_matrix(size)
    if method == "occurrence":
        matrix[matrix > 0] = 1
    elif method == "gravity":
        with np.errstate(divide="ignore"):
            denom = np.power(matrix, gamma)
            matrix = scale / denom
            matrix[denom == 0] = 0
    else:
        matrix_ = scale * np.exp(-2 * matrix / gamma)
        matrix = np.where(matrix > 0, matrix_, 0)

    path = gcore.tempfile()
    global TMPFILE
    TMPFILE = path

    with open(path, "w") as f:
        f.write(write_filter(matrix))
    gcore.message(_("Running development pressure filter..."))
    gcore.run_command("r.mfilter",
                      input=rmfilter_inp,
                      output=rmfilter_out,
                      filter=path)

    if flags["n"]:
        gcore.run_command(
            "g.region",
            n=region["n"],
            s=region["s"],
            e=region["e"],
            w=region["w"],
        )
        grast.mapcalc(
            exp="{out} = if(isnull({temp_null}), {rmfilter_out}, null())".
            format(temp_null=temp_map_nulls,
                   rmfilter_out=rmfilter_out,
                   out=output))
        gcore.del_temp_region()

    grast.raster_history(output)