[GRASS-user] scripting mapcalc

Glynn Clements glynn at gclements.plus.com
Fri Mar 6 08:47:43 EST 2009


Nikos Alexandris wrote:

> Nikos:
> > > Try this:
> > > r.mapcalc river="if(river==$old, $new, null())"
> 
> 
> Glynn:
> > Note that this won't work in 7.0, where r.mapcalc uses the parser. It
> > will complain that r.mapcalc doesn't have a river=... option.
> 
> > For portability, always:
> 
> > 1. quote the entire expression, and
> > 2. insert a space before the first = sign, e.g.:
> 
> > 	r.mapcalc "river = if(river==$old, $new, null())"
> 
> > This will work with all versions of r.mapcalc.
> 
> 
> Thanks Glynn.
> 
> I assume the above tips are valid for "normal" r.mapcalc use, that is
> not within from a script.

The above applies both to scripting and interactive use.

> Having a space before the 1st = sign is in addition more clear/easy
> to read when it comes to lots and long r.mapcalc one-liners, one
> after another.

In general, it's preferable to do as much as possible in each
r.mapcalc command. E.g. rather than:

	r.mapcalc "$GIS_OPT_OUTPUT.r = r#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * r#$GIS_OPT_SECOND"
	r.mapcalc "$GIS_OPT_OUTPUT.g = g#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * g#$GIS_OPT_SECOND"
	r.mapcalc "$GIS_OPT_OUTPUT.b = b#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * b#$GIS_OPT_SECOND"

use:

	r.mapcalc <<EOF
	$GIS_OPT_OUTPUT.r = r#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * r#$GIS_OPT_SECOND
	$GIS_OPT_OUTPUT.g = g#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * g#$GIS_OPT_SECOND
	$GIS_OPT_OUTPUT.b = b#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * b#$GIS_OPT_SECOND
	EOF

as the latter will read each input map only once.

It should only be necessary to use multiple, consecutive r.mapcalc
commands if each command uses the output map(s) from the previous
command.

Even then, note that a top-level assignment treats the LHS as both an
output map and a variable, and you can use the variable in subsequent
commands, e.g.:

	r.mapcalc <<EOF
	outmap = ...
	outmap_i = round(outmap)
	EOF

However, you can't use any modifiers (neighbourhood, category, RGB,
etc) in this way, as modifiers only work on maps, not variables, and
the output map isn't available as an input map until r.mapcalc
completes.

-- 
Glynn Clements <glynn at gclements.plus.com>


More information about the grass-user mailing list