I need to iteratively add each raster map of viewshed analysis obtained from a series of single observer locations. For this i used grass.mapcalc with Python (GRASS 7 for Windows). However, my problem is that in grass.mapcalc you cannot allow functions like the following that we do apply in normal programming.

grass.mapcalc("viewshedN = viewshed + ViewshedN", overwrite = True, quiet = True)

Therefore, i have a trouble in adding each raster iteratively. Is it possible to add an incremental number to the output each time a new raster created? I just tried this in a loop with an integer variable but failed (parse error) in the following code. Is there any other work around/ method or alternative to add each raster result iteratively in GRASS with Python?

formula = 'viewshed' + str(i)          
grass.mapcalc(formula, overwrite = True, quiet = True)

1 Answer 1


Here the correct syntax:

#!/usr/bin/env python
# r.mapcalc example in Python

import sys
import os
import atexit

import grass.script as grass

def cleanup():

def main():

    return 0

if __name__ == "__main__":
    options, flags = grass.parser()

    inmap = "slope"
    outmap = "slope_div10"
    # some junk example calculation
    grass.mapcalc("$outmap = float($inmap / $value)", inmap = inmap, outmap = outmap, value = 10.0)


And the result:

GRASS 7.0.svn (nc_spm_08):~ > g.region rast=slope
GRASS 7.0.svn (nc_spm_08):~ > python mapcalc.py 

GRASS 7.0.svn (nc_spm_08):~ > r.info -r slope

GRASS 7.0.svn (nc_spm_08):~ > r.info -r slope_div10

See also the Wiki page: http://grasswiki.osgeo.org/wiki/GRASS_Python_Scripting_Library#r.mapcalc_example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.