2

I've been trying to write a script creating binary maps:

a=raw_input ("enter a threshold") 
b=float(a) 
grass.run_command('r.mapcalculator', formula="**'base_map'>=b**", outfile='map'+str(a), overwrite=True) 

When I'm trying to execute it there's an error message :

Invalid map
Parse error 

Obviously, when the relevant part of the code is changed (e.g. formula="'base_map'>=**0.7**") everything is working fine. However, my goal was to write a script creating a map automatically when the "a" (the threshold) is provided.

4
  • I'm really not an expert, but is it possible that the formula is passed as such to Grass: "base_map >= b" (where you actually would like "base_map >= value_of_b"). Maybe you should somehow escape "b"? Just my 2 cents... Commented Mar 17, 2012 at 10:06
  • this is indeed a crucial question. how to "tell" grass to treat "b" as a value provided by the user (a=raw_input, b=float(a)) rather than a map (which obviously does not exist? as you can see I'm not an expert either
    – Dawid
    Commented Mar 17, 2012 at 10:21
  • Have you already made som tries such as "base_map >= " b? I haven't ever found any extensive documentation on the Grass API for python, so my first guess would be to try a few options like this... But maybe someone more clever than me has a more clever idea! Commented Mar 17, 2012 at 11:08
  • This is a FAQ. May I suggest printing out the value of formula? Specifically, display the value of the expression "**'base_map'>=b**". I think the problem and its solution will then immediately be clear.
    – whuber
    Commented Mar 17, 2012 at 14:51

2 Answers 2

5

The GRASS Python library uses the command grass.mapcalc, which is more along the lines of what you're looking for. It takes a string that is the same as the string you'd enter manually at the command line. Therefore if I'd enter the following string at the command line in GRASS:

r.mapcalc 'new_map = old_map - older_map * 32'

I could use the following line in Python to do the same thing:

import grass.script as grass
grass.mapcalc('new_map = old_map - older_map * 32')

So if you're wanting to construct a command for r.mapcalc in Python, try putting it together as a string. Here's an adapted version of your code:

a = raw_input("Enter a threshold: ") 
formula = 'map' + a + ' = base_map >= ' + a
grass.mapcalc(formula) 
1

Apparently the following works:

grass.mapcalc("$x=$A>=$b", x='output_map'+str(a), A='base_map', b=b)

in older versions of GRASS, the output will be saved as 'expression' so it is wise to copy and rename it before running the code again.

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.