[GRASS-dev] Re: grass-dev Digest, Vol 68, Issue 41

Michael Barton michael.barton at asu.edu
Thu Oct 27 12:13:59 EDT 2011




On Oct 27, 2011, at 10:00 AM, <grass-dev-request at lists.osgeo.org> wrote:

> Date: Wed, 26 Oct 2011 20:30:23 +0100
> From: Glynn Clements <glynn at gclements.plus.com>
> Subject: Re: [GRASS-dev] r.mapcalc in Python script (parse error)
> To: Margherita Di Leo <dileomargherita at gmail.com>
> Cc: grass-dev at lists.osgeo.org
> Message-ID: <20136.24527.829595.733755 at cerise.gclements.plus.com>
> Content-Type: text/plain; charset=us-ascii
> 
> 
> Margherita Di Leo wrote:
> 
>> I need a little help with r.mapcalc syntax in Python script. I want to
>> convert the following formula:
>> 
>> grass.run_command('r.mapcalculator', amap = r_stream+'_nothin' , formula =
>> '%s*%s' % (r_stream+'_nothin', r_mask) , outfile = r_stream+'_nothin',
>> overwrite = True)
>> 
>> I want to use r.mapcalc instead of r.mapcalculator. So I write:
>> 
>> grass.mapcalc("$r_stream_nothin = $r_stream_nothin * $r_mask",
>>                      r_mask = r_mask,
>>                      r_stream_nothin = r_stream+'_nothin')
>> 
>> but I get parse error. What's the correct way to do this? The aim is to add
>> the suffix '_nothin' to the existing variable name r_stream.
> 
> There's nothing obviously wrong with the above code, although you
> should probably quote the map names, i.e.:
> 
>        grass.mapcalc("'$r_stream_nothin' = '$r_stream_nothin' * '$r_mask'",
>         ...
> 
> Map names which contain symbols need to be quoted, otherwise e.g. a
> map named "map-name" will be parsed as a subtraction.
> 
> Check the values of r_stream and r_mask with e.g.:
> 
>        print repr(r_stream), repr(r_mask)
> 
> Running 'g.gisenv set=DEBUG=1' prior to the script will enable some
> debugging information, including the exact r.mapcalc command.
> 
> Also, using the same map as both input and output is unwise. It
> appears to work, at least for simple cases, but shouldn't be relied
> upon.
> 
> --
> Glynn Clements <glynn at gclements.plus.com>

Hi,

You've got the string substitution wrong may need to use more string substitution. I'm assuming that r_stream is a variable

The first statement is...

grass.run_command('r.mapcalculator', amap = r_stream+'_nothin' , formula =
'%s*%s' % (r_stream+'_nothin', r_mask) , outfile = r_stream+'_nothin',
overwrite = True)

You should rewrite it as...

grass.run_command('r.mapcalculator', amap = '%s_nothin' % r_stream , formula =
'%s_nothin' * %s' % (r_stream, r_mask) , outfile = '%s_nothin' % r_stream,
overwrite = True)

You could do something similar with r.mapcalc instead of r.mapcalculator (note that r.mapcalculator is no longer present in GRASS 7)


In the second statement, I think the format should be...


grass.mapcalc("'%s_nothin' = '%s_nothin' * '%s'" % (r_stream, r,stream, r_mask))

Using the "$" does not work on my system at least. 

Michael



More information about the grass-dev mailing list