NAME

r.mapcalc - Raster map layer data calculator.
(GRASS Raster Program)

SYNOPSIS

r.mapcalc
r.mapcalc [result=expression]

DESCRIPTION

r.mapcalc performs arithmetic on raster map layers. New raster map layers can be created which are arithmetic expressions involving existing raster map layers, integer or floating point constants, and functions.

PROGRAM USE

If used without command line arguments, r.mapcalc will read its input, one line at a time, from standard input (which is the keyboard, unless r.directed from a file or across a pipe). Otherwise, the expression on the command line is evaluated. r.mapcalc expects its input to have the form:

result=expression

where result is the name of a raster map layer to contain the result of the calculation and expression is any legal arithmetic expression involving existing raster map layers, integer or floating point constants, and functions known to the calculator. Parentheses are allowed in the expression and may be nested to any depth. result will be created in the user's current mapset.

The formula entered to r.mapcalc by the user is recorded both in the result map title (which appears in the category file for result) and in the history file for result.

Some characters have special meaning to the command shell. If the user is entering input to r.mapcalc on the command line, expressions should be enclosed within single quotes. See NOTES, below.

OPERATORS AND ORDER OF PRECEDENCE

The following operators are supported:
     Operator   Meaning                            Type        Precedence
     -----------------------------------------------------------------------
     %          modulus (remainder upon division)   Arithmetic  4
     /          division                            Arithmetic  4
     *          multiplication                      Arithmetic  4
     +          addition                            Arithmetic  3
     -          subtraction                         Arithmetic  3
     ==         equal                               Logical     2
     !=         not equal                           Logical     2
     >          greater than                        Logical     2
     >=         greater than or equal               Logical     2
     <          less than                           Logical     2
     <=         less than or equal                  Logical     2
     &&         and                                 Logical     1
     ||         or                                  Logical     1

The operators are applied from left to right, with those of higher precedence applied before those with lower precedence. Division by 0 and modulus by 0 are acceptable and give a 0 result. The logical operators give a 1 result if the comparison is true, 0 otherwise.

RASTER MAP LAYER NAMES

Anything in the expression which is not a number, operator, or function name is taken to be a raster map layer name. Examples:

elevation
x3
3d.his

Most GRASS raster map layers meet this naming convention. However, if a raster map layer has a name which conflicts with the above rule, it should be quoted. For example, the expression

x = a-b

would be interpreted as: x equals a minus b, whereas

x = "a-b"

would be interpreted as: x equals the raster map layer named a-b

Also

x = 3107

would create x filled with the number 3107, while

x = "3107"

would copy the raster map layer 3107 to the raster map layer x.

Quotes are not required unless the raster map layer names look like numbers or contain operators, OR unless the program is run non-interactively. Examples given here assume the program is run interactively. See NOTES, below.

r.mapcalc will look for the raster map layers according to the user's current mapset search path. It is possible to override the search path and specify the mapset from which to select the raster map layer. This is done by specifying the raster map layer name in the form:

name@mapset

For example, the following is a legal expression:

result = x@PERMANENT / y@SOILS

The mapset specified does not have to be in the mapset search path. (This method of overriding the mapset search path is common to all GRASS commands, not just r.mapcalc.)

THE NEIGHBORHOOD MODIFIER

Maps and images are data base files stored in raster format, i.e., two-dimensional matrices of integer values. In r.mapcalc, maps may be followed by a neighborhood modifier that specifies a relative offset from the current cell being evaluated. The format is map[r,c], where r is the row offset and c is the column offset. For example, map[1,2] refers to the cell one row below and two columns to the right of the current cell, map[-2,-1] refers to the cell two rows above and one column to the left of the current cell, and map[0,1] refers to the cell one column to the right of the current cell. This syntax permits the development of neighborhood-type filters within a single map or across multiple maps.

RASTER MAP LAYER VALUES FROM THE CATEGORY FILE

Sometimes it is desirable to use a value associated with a category's contents instead of the category value itself. If a raster map layer name is preceded by the @ operator, then the labels in the category file for the raster map layer are used in the expression instead of the category value.

For example, suppose that the raster map layer soil.ph (representing soil pH values) has a category file with labels as follows:

cat	label
------------------
0	no data

1	1.4
2	2.4
3	3.5
4	5.8
5	7.2
6	8.8
7	9.4

Then the expression:

result = @soils.ph * 10

would produce a result with category values 0, 14, 24, 35, 58, 72, 88 and 94.

Note that this operator may only be applied to raster map layers and produces a floating point value in the expression. Also the category label must start with a valid number. Missing labels, or labels that do not start with a number will (silently) produce a 0 value for that category.

GREY SCALE EQUIVALENTS AND COLOR SEPARATES

It is often helpful to manipulate the colors assigned to map categories. This is particularly useful when the spectral properties of cells have meaning (as with imagery data), or when the map category values represent real quantities (as when category values reflect true elevation values). Map color manipulation can also aid visual recognition, and map printing.

The # operator can be used to either convert map category values to their grey scale equivalents or to extract the red, green, or blue components of a raster map layer into separate raster map layers.

result = #map

converts each category value in map to a value in the range 0-255 which represents the grey scale level implied by the color for the category. If the map has a grey scale color table, then the grey level is what #map evaluates to. Otherwise, it is computed as:

.18 * red + .81 * green + .01 * blue

The # operator has three other forms: r#map, g#map, b#map. These extract the red, green, or blue components in the named raster map, respectively. The GRASS shell script blend.sh extracts each of these components from two raster map layers, and combines them by a user-specified percentage. These forms allow color separates to be made. For example, to extract the red component from map and store it in the new 0-255 map layer red, the user could type:

red = r#map

To assign this map grey colors type:

r.colors map=red color=rules
black
white

To assign this map red colors type:

r.colors map=red color=rules
black
red

FUNCTIONS

The functions currently supported are listed in the table below. The type of the result is indicated in the last column. F means that the functions always results in a floating point value, I means that the function gives an integer result, and * indicates that the result is float if any of the arguments to the function are floating point values and integer if all arguments are integer.

function		description					type
---------------------------------------------------------------------------
abs(x)			return absolute value of x			*
atan(x)			inverse tangent of x (result is in degrees)	F
cos(x)			cosine of x (x is in degrees)			F
eval([x,y,...,]z)	evaluate values of listed expr, pass results to z
exp(x)			exponential function of x			F
exp(x,y)		x to the power y				F
float(x)		convert x to floating point			F
if			decision options:				*
if(x)			1 if x not zero, 0 otherwise
if(x,a)			a if x not zero, 0 otherwise
if(x,a,b)		a if x not zero, b otherwise
if(x,a,b,c)		a if x > 0, b if x is zero, c if x < 0
int(x)			convert x to integer [ truncates ]		I
log(x)			natural log of x				F
log(x,b)		log of x base b					F
max(x,y[,z...])		largest value of those listed			*
median(x,y[,z...])	median value of those listed			*
min(x,y[,z...])		smallest value of those listed			*
round(x)		round x to nearest integer			I
sin(x)			sine of x (x is in degrees)			F
sqrt(x)			square root of x				F
tan(x)			tangent of x (x is in degrees)			F

FLOATING POINT VALUES IN THE EXPRESSION

Floating point numbers are allowed in the expression. A floating point number is a number which contains a decimal point:
2.3   12.   .81
Floating point values in the expression are handled in a special way. With arithmetic and logical operators, if either operand is float, the other is converted to float and the result of the operation is float. This means, in particular that division of integers results in a (truncated) integer, while division of floats results in an accurate floating point value. With functions of type * (see table above), the result is float if any argument is float, integer otherwise.

However, GRASS raster map layers can only store integer values. If the final value of the expression is a floating point value, this value is rounded to the nearest integer before storing it in the result raster map layer.

Note that raster map layers in the expression are considered to be integers.

EXAMPLES

To compute the average of two raster map layers a and b:
	ave = (a + b)/2
To form a weighted average:
	ave = (5*a + 3*b)/8.0
To produce a binary representation of the raster map layer a so that category 0 remains 0 and all other categories become 1:
	mask = a/a
This could also be accomplished by:
	mask = if(a)
To mask raster map layer b by raster map layer a:
	result = if(a,b)

REGION/MASK

The user must be aware of the current geographic region and current mask settings when using r.mapcalc. All raster map layers are read into the current geographic region masked by the current mask. If it is desired to modify an existing raster map layer without involving other raster map layers, the geographic region should be set to agree with the cell header for the raster map layer. For example, suppose it is determined that the elevation raster map layer must have each category value increased by 10 meters. The following expression is legal and will do the job:
	new_elevation = elevation + 10
Since a category value of 0 is used in GRASS for locations which do not exist in the raster map layer, the new raster map layer will contain the category value 10 in the locations that did not exist in the original elevation. Therefore, in this example, it is essential that the boundaries of the geographic region be set to agree with the cell header.

However, if there is a current mask, then the resultant raster map layer is masked when it is written; i.e., 0 category values in the mask force zero values in the output.

NOTES

Extra care must be taken if the expression is given on the command line. Some characters have special meaning to the UNIX shell. These include, among others:

* ( ) > & |

It is advisable to put single quotes around the expression; e.g.:

	result = 'elevation * 2'
Without the quotes, the *, which has special meaning to the UNIX shell, would be altered and r.mapcalc would see something other than the *.

If the input comes directly from the keyboard and the result raster map layer exists, the user will be asked if it can be overwritten. Otherwise, the result raster map layer will automatically be overwritten if it exists.

Quoting result is not allowed. However, it is never necessary to quote result since it is always taken to be a raster map layer name.

For formulas that the user enters from standard input (rather than from the command line), a line continuation feature now exists. If the user adds \e to the end of an input line, r.mapcalc assumes that the formula being entered by the user continues on to the next input line. There is no limit to the possible number of input lines or to the length of a formula.

If the r.mapcalc formula entered by the user is very long, the map title will contain only some of it, but most (if not all) of the formula will be placed into the history file for the result map.

When the user enters input to r.mapcalc non-interactively on the command line, the program will not warn the user not to overwrite existing map layers. Users should therefore take care to assign program outputs raster file names that do not yet exist in their current mapsets.

BUGS

Continuation lines must end with a \ and have NO trailing white space (blanks or tabs). If the user does leave white space at the end of continuation lines, the error messages produced by r.mapcalc will be meaningless and the equation will not work as the user intended.

Error messages produced by r.mapcalc are almost useless. In future, r.mapcalc should make some attempt to point the user to the offending section of the equation, e.g.:

	x = a * b ++ c

	ERROR: somewhere in line 1: ...  b ++ c ...

Currently, there is no comment mechanism in r.mapcalc. Perhaps adding a capability that would cause the entire line to be ignored when the user inserted a # at the start of a line as if it were not present, would do the trick.

The function should require the user to type "end" or "exit" instead of simply a blank line. This would make separation of multiple scripts separable by white space.

SEE ALSO

r.mapcalc: An Algebra for GIS and Image Processing, by Michael Shapiro and Jim Westervelt, U.S. Army Construction Engineering Research Laboratory (March/1991).

Grey scale conversion is based on the C.I.E. x,y,z system where y represents luminance. See "Fundamentals of Digital Image Processing," by Anil K. Jain (Prentice Hall, NJ, 1989; p 67).

blend.sh
g.region
r.colors
r.combine
r.infer
r.mask
r.weight
r.xy

AUTHOR

Michael Shapiro, U.S.Army Construction Engineering Research Laboratory