[GRASS-dev] eval option in r.mapcalc in a python script

Glynn Clements glynn at gclements.plus.com
Mon Jan 18 13:19:44 PST 2016


Paulo van Breugel wrote:

>  From the r.mapcalc manual, the 'eval' option is described to run more 
> complex expressions. But I wonder how I apply the example below in a 
> python script?
> 
> r.mapcalc << EOF
> eval(elev_200 = elevation - 200, \
> elev_5 = 5 * elevation, \
> elev_p = pow(elev_5, 2))
> elevation_result = (0.5 * elev_200) + 0.8 * elev_p
> EOF

Use grass.script.mapcalc().

The first parameter is a template string, which is passed to
string.Template() (see the Python documentation for the string module)
then instantiated using any additional keyword arguments. This can be
used if you need to be able to substitute parameters into the
expression.

For complex expressions, you can use any of Python's features to
construct the expression. E.g.

        assignments = [
            "elev_200 = elevation - 200",
            "elev_5 = 5 * elevation",
            "elev_p = pow(elev_5, 2)"]
        result = "elevation_result = (0.5 * elev_200) + 0.8 * elev_p"
        expr = "eval(" + ",".join(assignments) + ");" + result
        gscript.mapcalc(expr)

This may be useful if you need to be able to dynamically manipulate
the structure of the expression rather than just parameters.

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


More information about the grass-dev mailing list