r.mapcalc(1)
๐ฆ r.mapcalc โ the raster map calculator, bestie edition
okay so real quick, this is r.mapcalc from the GRASS GIS User's Manual, section 1 (that's the manual name, we're folding it in, you're welcome ๐
). It's the raster map calculator and it literally ate. Let's go.
โจ NAME โจ
r.mapcalc โ Raster map calculator. ๐งฎ
๐ธ KEYWORDS ๐ธ
raster, algebra
๐ SYNOPSIS ๐
r.mapcalc
r.mapcalc --help
r.mapcalc [-sl] [expression=string] [region=string] [file=name]
[seed=integer] [--overwrite] [--help] [--verbose] [--quiet] [--ui]
โญ Flags โญ
-sโ Generate random seed (result is non-deterministic). it's giving chaos, and that's the point ๐ฒ-lโ List input and output maps ๐--overwriteโ Allow output files to overwrite existing files. yes queen, bulldoze it ๐--helpโ Print usage summary--verboseโ Verbose module output--quietโ Quiet module output ๐คซ--uiโ Force launching GUI dialog
๐ซถ Parameters ๐ซถ
expression=stringโ Expression to evaluateregion=stringโ The computational region that should be used.- Options:
current,intersect,union - Default:
current current: current uses the current region of the mapsetintersect: intersect computes the intersection region between all input maps and uses the smallest resolutionunion: union computes the union extent of all map regions and uses the smallest resolution
- Options:
file=nameโ File containing expression(s) to evaluateseed=integerโ Seed forrand()function ๐ฑ
๐ 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. no cap, that's the whole vibe. ๐ฅ
๐ง Program use
r.mapcalc expression 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 (except result itself), 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. ๐
As expression= is the first option, it is the default. This means that passing an expression on the command line is possible as long as the expression is quoted and a space is included before the first = sign. Example (foo is the resulting map):
r.mapcalc "foo = 1"
or:
r.mapcalc 'foo = 1'
An unquoted expression (i.e. split over multiple arguments) won't work, nor will omitting the space before the = sign:
r.mapcalc 'foo=1'
Sorry, <foo> is not a valid parameter
๐จ bestie. the SPACE before the = is not optional. skip it and the whole thing falls apart. we do not skip the space.
To read command from the file, use file= explicitly, e.g.:
r.mapcalc file=file
or:
r.mapcalc file=- < file
or:
r.mapcalc file=- <<EOF
foo = 1
EOF
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. receipts are kept, always ๐
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.
๐ Computational regions in r.mapcalc
By default r.mapcalc uses the current region as computational region that was set with g.region for processing. Sometimes it is necessary to use a region that is derived from the raster maps in the expression to set the computational region. This is of high importance for modules that use r.mapcalc internally to process time series of satellite images that all have different spatial extents. A module that requires this feature is t.rast.algebra. The region option of r.mapcalc was implemented to address this requirement. It allows computing and using a region based on all raster maps in an expression. Three modes are supported:
- Setting the
regionparameter tocurrentwill result in the use of the current region as computational region. This is the default. The current region can be set withg.region. - The parameter
unionwill forcer.mapcalcto compute the disjoint union of all regions from raster maps specified in the expression. This computed region will then be used as computational region at runtime. The region of the mapset will not be modified. The smallest spatial resolution of all raster maps will be used for processing. - The parameter
intersectwill forcer.mapcalcto compute the intersection of all regions from raster maps specified in the expression. This computed region will then be used as computational region at runtime. The region of the mapset will not be modified. The smallest spatial resolution of all raster maps will be used for processing.
๐ Operators and order of precedence
The following operators are supported:
-โ negation, Arithmetic, precedence 12~โ one's complement, Bitwise, precedence 12!โ not, Logical, precedence 12^โ exponentiation, Arithmetic, precedence 11%โ modulus, Arithmetic, precedence 10/โ division, Arithmetic, precedence 10*โ multiplication, Arithmetic, precedence 10+โ addition, Arithmetic, precedence 9-โ subtraction, Arithmetic, precedence 9<<โ left shift, Bitwise, precedence 8>>โ right shift, Bitwise, precedence 8>>>โ right shift (unsigned), Bitwise, precedence 8>โ greater than, Logical, precedence 7>=โ greater than or equal, Logical, precedence 7<โ less than, Logical, precedence 7<=โ less than or equal, Logical, precedence 7==โ equal, Logical, precedence 6!=โ not equal, Logical, precedence 6&โ bitwise and, Bitwise, precedence 5|โ bitwise or, Bitwise, precedence 4&&โ logical and, Logical, precedence 3&&&โ logical and[1], Logical, precedence 3||โ logical or, Logical, precedence 2|||โ logical or[1], Logical, precedence 2?:โ conditional, Logical, precedence 1
(modulus is the remainder upon division)
[1] The &&& and ||| operators handle null values differently to other operators. See the section entitled NULL support below for more details.
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 NULL 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. ๐
The neighborhood modifier cannot be used on maps generated within same r.mapcalc command run (see "KNOWN ISSUES" section).
๐ read that again. neighborhood modifier + map made in the SAME run = nope. don't do it.
๐ฆ Raster map layer values from the category file
Sometimes it is desirable to use a value associated with a category's label 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
would produce a result with category values 0, 1.4, 2.4, 3.5, 5.8, 7.2, 8.8 and 9.4.
Note that this operator may only be applied to raster map layers and produces a floating point value in the expression. Therefore, the category label must start with a valid number. If the category label is integer, it will be represented by a floating point number. I the category label does not start with a number or is missing, it will be represented by NULL (no data) in the resulting raster map. ๐
๐ธ 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. ๐จ
okay so the # operator โ she's a dual-threat icon and honestly we love her for it ๐
She can either convert map category values into their grey scale equivalents, OR she can pull the red, green, or blue components out of a raster map layer and drop each one into its own separate raster map layer. Two jobs, zero complaints.
result = #map
This one takes every category value in map and converts it to a value in the range 0-255, which is the grey scale level that the color for that category implies. If the map already has a grey scale color table, then the grey level is literally what #map evaluates to. If not, it gets computed as:
0.10 * red + 0.81 * green + 0.01 * blue
Or alternatively, you can use:
result = y#map
to get the NTSC weightings:
0.30 * red + 0.59 * green + 0.11 * blue
Orrr you can use:
result = i#map
for equal weightings:
0.33 * red + 0.33 * green + 0.33 * blue
Now 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 r.blend extracts each of these components from two raster map layers, and combines them by a user-specified percentage. These forms let you make color separates. 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 below. The type of the result is in the last bit of each line. F means the function always results in a floating point value, I means the function gives an integer result, and * means the result is float if any of the arguments to the function are floating point values, and integer if all arguments are integer. (Some of them don't declare a type at all, and that's just how it is bestie ๐)
abs(x)โ return absolute value ofxโ type*acos(x)โ inverse cosine ofx(result is in degrees) โ typeFasin(x)โ inverse sine ofx(result is in degrees) โ typeFatan(x)โ inverse tangent ofx(result is in degrees) โ typeFatan(x,y)โ inverse tangent ofy/x(result is in degrees) โ typeFceil(x)โ the smallest integral value not less thanxโ type*cos(x)โ cosine ofx(xis in degrees) โ typeFdouble(x)โ convertxto double-precision floating point โ typeFeval([x,y,...,]z)โ evaluate values of listed expr, pass results tozexp(x)โ exponential function ofxโ typeFexp(x,y)โxto the poweryโ typeFfloat(x)โ convertxto single-precision floating point โ typeFfloor(x)โ the largest integral value not greater thanxโ type*graph(x,x1,y1[x2,y2..])โ convert thexto aybased on points in a graph โ typeFgraph2(x,x1[,x2,..],y1[,y2..])โ alternative form ofgraph()โ typeFifโ decision options: โ type*if(x)โ 1 ifxnot zero, 0 otherwiseif(x,a)โaifxnot zero, 0 otherwiseif(x,a,b)โaifxnot zero,botherwiseif(x,a,b,c)โaifx > 0,bifxis zero,cifx < 0
int(x)โ convertxto integer [ truncates ] โ typeIisnull(x)โ check ifx = NULLlog(x)โ natural log ofxโ typeFlog(x,b)โ log ofxbasebโ typeFmax(x,y[,z...])โ largest value of those listed โ type*median(x,y[,z...])โ median value of those listed โ type*min(x,y[,z...])โ smallest value of those listed โ type*mod(x,y)โ return the modulus (the remainder) ofx/yโ type*mode(x,y[,z...])โ mode value of those listed โ type*nmax(x,y[,z...])โ largest value of those listed, excluding NULLs โ type*nmedian(x,y[,z...])โ median value of those listed, excluding NULLs โ type*nmin(x,y[,z...])โ smallest value of those listed, excluding NULLs โ type*nmode(x,y[,z...])โ mode value of those listed, excluding NULLs โ type*not(x)โ 1 ifxis zero, 0 otherwisepow(x,y)โxto the poweryโ type*rand(a,b)โ random valuex:a <= x < bโ type*round(x)โ roundxto nearest integer โ typeIround(x,y)โ roundxto nearest multiple ofyround(x,y,z)โ roundxto nearesty*i+zfor some integerisin(x)โ sine ofx(xis in degrees) โ typeFsqrt(x)โ square root ofxโ typeFtan(x)โ tangent ofx(xis in degrees) โ typeFxor(x,y)โ exclusive-or (XOR) ofxandyโ typeI
And the internal variables (she keeps them on the inside, very mysterious ๐):
row()โ current row of moving window โ typeIcol()โ current col of moving window โ typeInrows()โ number of rows in computation region โ typeIncols()โ number of columns in computation region โ typeIx()โ current x-coordinate of moving window โ typeFy()โ current y-coordinate of moving window โ typeFewres()โ current east-west resolution โ typeFnsres()โ current north-south resolution โ typeFarea()โ area of current cell in square meters โ typeFnull()โ NULL value
Heads up bestie: therow()andcol()indexing starts with 1. Not zero. One. Don't come for me, that's just the rules.
๐ข Data types and their precision ๐ข
There are three data types you can use inside a mapcalc expression. Each one is defined with a certain precision and lives inside a certain value range. Here's the tea on precision and value range on AMD64 (x86-64) architectures compiled with GCC/CLANG. Note that even though this setting is the most frequent one, the ranges could totally differ for different architectures, so don't @ me if you're on something weird.
intโ a 32-bit integer with a range from -2,147,483,647 to +2,147,483,647. The value-2,147,483,648is reserved for NODATA.floatโ a 32-bit float (Float32) with a range from -3.4E38 to 3.4E38. However, the integer precision can be only ensured between -16,777,216 and 16,777,216. If your raster overpasses this range, it is strongly suggested to use the typedoubleinstead.doubleโ a 64-bit float (Float64) with a range from -1.79E308 to 1.79E308. It is 8 bytes, 15-17 digits precision.nullโ NULL value. Refer to section "NULL support" below.
โ ๏ธ Note that the value counter wraps around when the value overflows its range. E.g., if your expression isa = int(2147483648), you will get NULL value. For expressiona = int(2147483649), you will reach the lowest value possible instead, i.e.-2147483647.
๐ Floating point values in the expression ๐
Floating point numbers are allowed in the expression, periodt. A floating point number is a number which contains a decimal point:
2.3 12.0 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 the table above), the result is float if any argument is float, integer otherwise.
Note: If you calculate with integer numbers, the resulting map will be integer. If you want to get a float result, add the decimal point to integer number(s).
If you want floating point division, at least one of the arguments has to be a floating point value. Multiplying one of them by 1.0 will produce a floating-point result, as will using float():
r.mapcalc "ndvi = float(lsat.4 - lsat.3) / (lsat.4 + lsat.3)"
๐ณ๏ธ NULL support ๐ณ๏ธ
- Division by zero should result in NULL.
- Modulus by zero should result in NULL.
- NULL-values in any arithmetic or logical operation should result in NULL. (however,
&&&and|||are treated specially, as described below). - The
&&&and|||operators observe the following axioms even whenxis NULL:
x &&& false == false
false &&& x == false
x ||| true == true
true ||| x == true
- NULL-values in function arguments should result in NULL (however,
if(),eval()andisnull()are treated specially, as described below). - The
eval()function always returns its last argument - The situation for
if()is:
if(x)
NULL if x is NULL; 0 if x is zero; 1 otherwise
if(x,a)
NULL if x is NULL; a if x is non-zero; 0 otherwise
if(x,a,b)
NULL if x is NULL; a if x is non-zero; b otherwise
if(x,n,z,p)
NULL if x is NULL; n if x is negative;
z if x is zero; p if x is positive
- The (new) function
isnull(x)returns: 1 ifxis NULL; 0 otherwise. The (new) functionnull()(which has no arguments) returns an integer NULL. - Non-NULL, but invalid, arguments to functions should result in NULL.
Examples:
log(-2)
sqrt(-2)
pow(a,b) where a is negative and b is not an integer
NULL support: Please note that any math performed with NULL cells always results in a NULL value for these cells. If you want to replace a NULL cell on-the-fly, use the isnull() test function in a if-statement.
Example: The users wants the NULL-valued cells to be treated like zeros. To add maps A and B (where B contains NULLs) to get a map C the user can use a construction like:
C = A + if(isnull(B),0,B)
NULL and conditions:
For the one argument form:
if(x) = NULL if x is NULL
if(x) = 0 if x = 0
if(x) = 1 otherwise (i.e. x is neither NULL nor 0).
For the two argument form:
if(x,a) = NULL if x is NULL
if(x,a) = 0 if x = 0
if(x,a) = a otherwise (i.e. x is neither NULL nor 0).
For the three argument form:
if(x,a,b) = NULL if x is NULL
if(x,a,b) = b if x = 0
if(x,a,b) = a otherwise (i.e. x is neither NULL nor 0).
And for the four argument form:
if(x,a,b,c) = NULL if x is NULL
if(x,a,b,c) = a if x > 0
if(x,a,b,c) = b if x = 0
if(x,a,b,c) = c if x < 0
Okay so big general rule: pretty much all operators and most functions hand you back NULL if any of their arguments are NULL. Like, any single one. That's the vibe.
The exceptions โ the iconic trio โ are if(), isnull() and eval(). ๐
isnull() gives you 1 if its argument is NULL and 0 if it isn't. Wanna flip it? Use the ! operator, as in !isnull(x). That's the move.
Every form of if() returns NULL if the first argument is NULL. And the 2, 3 and 4 argument forms of if() return NULL if the "selected" argument is NULL, bestie, like:
if(0,a,b) = b regardless of whether a is NULL
if(1,a,b) = a regardless of whether b is NULL
eval() always returns its last argument, so it only ever returns NULL if that last argument is NULL. No drama, no surprises.
Note: you cannot test forNULLusing the==operator, because that returnsNULLif either or both arguments areNULL. So ifxandyare bothNULL, thenx == yandx != yare bothNULLrather than1and0. ๐ญ
And honestly that behaviour makes total sense if you think of NULL as standing in for an unknown quantity. Like, if x and y are both unknown, then whether x == y and whether x != y are also unknown โ you literally don't know if they have the same value, because you don't know either value. โจ
๐ NOTES ๐
๐ฅ๏ธ Usage from command line ๐ฅ๏ธ
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 *. ๐
๐งฎ Multiple computations ๐งฎ
In general, it's preferable to do as much as possible in each r.mapcalc command. E.g. rather than:
r.mapcalc "$GIS_OPT_OUTPUT.r = r#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * r#$GIS_OPT_SECOND"
r.mapcalc "$GIS_OPT_OUTPUT.g = g#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * g#$GIS_OPT_SECOND"
r.mapcalc "$GIS_OPT_OUTPUT.b = b#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * b#$GIS_OPT_SECOND"
use:
r.mapcalc <<EOF
$GIS_OPT_OUTPUT.r = r#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * r#$GIS_OPT_SECOND
$GIS_OPT_OUTPUT.g = g#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * g#$GIS_OPT_SECOND
$GIS_OPT_OUTPUT.b = b#$GIS_OPT_FIRST * .$GIS_OPT_PERCENT + (1.0 - .$GIS_OPT_PERCENT) * b#$GIS_OPT_SECOND
EOF
because the latter will read each input map only once. Efficiency queen behaviour. ๐
โช Backwards compatibility โช
For the backwards compatibility with GRASS 6, if no options are given, it manufactures file=- (which reads from stdin), so you can continue to use e.g.:
r.mapcalc < file
or:
r.mapcalc <<EOF
foo = 1
EOF
But unless you need compatibility with previous GRASS GIS versions, use file= explicitly, as stated above. Fr fr.
When the map name contains uppercase letter(s) or a dot which are not allowed to be in module option names, the r.mapcalc command will be valid also without quotes:
r.mapcalc elevation_A=1
r.mapcalc elevation.1=1
However, this syntax is not recommended as quotes as stated above more safe. Using quotes is both backwards compatible and valid in future. ๐ซถ
โจ๏ธ Interactive input in command line โจ๏ธ
For formulas that you enter from standard input (rather than from the command line), a line continuation feature now exists. If you add a backslash to the end of an input line, r.mapcalc assumes that the formula you're entering 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. Go off, write an essay. ๐
If the r.mapcalc formula you entered 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. iykyk.
๐ญ Raster MASK handling ๐ญ
r.mapcalc follows the common GRASS behavior of raster MASK handling, so the MASK is only applied when reading an existing GRASS raster map. This implies that, for example, the command:
r.mapcalc "elevation_exaggerated = elevation * 3"
create a map respecting the masked pixels if MASK is active.
However, when creating a map which is not based on any map, e.g. a map from a constant:
r.mapcalc "base_height = 200.0"
the created raster map is limited only by a computation region but it is not affected by an active MASK. This is expected because, as mentioned above, MASK is only applied when reading, not when writing a raster map.
If also in this case the MASK should be applied, an if() statement including the MASK should be used, e.g.:
r.mapcalc "base_height = if(MASK, 200.0, null())"
When testing MASK related expressions keep in mind that when MASK is active you don't see data in masked areas even if they are not NULL. See r.mask for details. ๐
๐ช eval function ๐ช
If the output of the computation should be only one map but the expression is so complex that it is better to split it to several expressions, the eval function can be used:
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
This example uses unix-like << EOF syntax to provide input to r.mapcalc.
Note that the temporary variables (maps) are not created and thus it does not matter whether they exists or not. In the example above, if map elev_200 exists it will not be overwritten and no error will be generated. The reason is that the name elev_200 now denotes the temporary variable (map) and not the existing map. The following parts of the expression will use the temporary elev_200 and the existing elev_200 will be left intact and will not be used. If a user want to use the existing map, the name of the temporary variable (map) must be changed. ๐
๐ Using the same map for input and output results ๐
A map cannot be used both as an input and as an output as in this invalid expression oldmap = oldmap + 1, instead a subsequent rename using g.rename is needed when the same name is desired:
r.mapcalc "newmap = oldmap + 1"
g.rename raster=newmap,oldmap
๐ฒ Random number generator initialization ๐ฒ
The pseudo-random number generator used by the rand() function can be initialised to a specific value using the seed option. This can be used to replicate a previous calculation.
Alternatively, it can be initialised from the system time and the PID using the -r flag. This should result in a different seed being used each time.
In either case, the seed will be written to the map's history, and can be seen using r.info.
If you want other people to be able to verify your results, it's preferable to use the seed option to supply a seed which is either specified in the script or generated from a deterministic process such as a pseudo-random number generator given an explicit seed. Science bestie behaviour, no cap. ๐ฌ
Note that therand()function will generate a fatal error if neither theseedoption nor the-sflag are given. ๐
๐ 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:
mapmask = a != 0
This could also be accomplished by:
mapmask = if(a)
To mask raster map layer b by raster map layer a:
result = if(a,b)
To change all values below 5 to NULL, keep 5 otherwise:
newmap = if(map<5, null(), 5)
To create a map with random values in a defined range (needs either the usage of -s flag or the seed parameter). The precision of the input values determines the output precision (the resulting raster map type):
# write result as integer map (CELL)
random_int = rand(-100,100)
# write result as double precision floating point map (DCELL)
random_dcell = rand(-100.0,100.0)
# write result as single precision floating point map (FCELL)
random_fcell = float(rand(-100.0,100.0))
The graph() function allows users to specify a x-y conversion using pairs of x,y coordinates. In some situations a transformation from one value to another is not easily established mathematically, but can be represented by a 2-D graph and then linearly interpolated. The graph() function provides the opportunity to accomplish this. An x-axis value is provided to the graph function along with the associated graph represented by a series of x,y pairs. The x values must be monotonically increasing (each larger than or equal to the previous). The graph function linearly interpolates between pairs. Any x value lower the lowest x value (i.e. first) will have the associated y value returned. Any x value higher than the last will similarly have the associated y value returned. Consider the request:
newmap = graph(map, 1,10, 2,25, 3,50)
X (map) values supplied and y (newmap) values returned:
0, 10
1, 10
1.5, 17.5
2.9, 47.5
4, 50
100, 50
๐ KNOWN ISSUES ๐
Okay bestie, gather round, because this is the part where we talk about the little gremlins living in the code. Not scary, justโฆ real. ๐ซถ
- Do NOT let the result variable on the left hand side of the equation show up again in the expression on the right hand side. Like, just don't. This is not the vibe:
mymap = if( mymap > 0, mymap, 0)
- Any maps generated by an
r.mapcalccommand only exist after the entire command has finished. Every map gets generated concurrently, row-by-row โ picture an implicitfor row in rows {...}wrapped around the whole expression. Which means the#,@, and[ ]operators cannot be used on a map generated within the samer.mapcalccommand run. So this (strikethrough code) does not work:
newmap = oldmap * 3.14
othermap = newmap[-1, 0] / newmap[1, 0]
- Continuation lines have to end with a
\and there must be no trailing white space (blanks or tabs). If you do leave white space hanging off the end of a continuation line, the error messagesr.mapcalcthrows at you will be meaningless and the equation will not do what you intended. This matters especially for theeval()function. iykyk. ๐ญ - Currently there is no comment mechanism in
r.mapcalc. Maybe someday there'll be a capability that just ignores the entire line when the user puts a#at the start of it, like it wasn't even there. That would do the trick. ๐ - The function should really require you to type
"end"or"exit"instead of just a blank line. That would make separating multiple scripts actually separable by white space. Manifesting it. โจ r.mapcalcdoes not print a warning when you do operations on NULL cells. Nope, not one. It's left entirely to you to use theisnull()function. No cap. ๐
๐ REFERENCES ๐
- r.mapcalc: An Algebra for GIS and Image Processing, by Michael Shapiro and Jim Westervelt, U.S. Army Construction Engineering Research Laboratory (March/1991).
- Performing Map Calculations on GRASS Data: r.mapcalc Program Tutorial, by Marji Larson, Michael Shapiro and Scott Tweddale, U.S. Army Construction Engineering Research Laboratory (December 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).
๐ SEE ALSO ๐
g.regionr.bitpatternr.blendr.colorsr.fillnullsr.mapcalc.simple
๐ AUTHORS ๐
- Michael Shapiro, U.S.Army Construction Engineering Research Laboratory
- Glynn Clements
๐ SOURCE CODE ๐
Available at: r.mapcalc source code (history)
Accessed: Saturday Jan 17 05:40:51 2026
Main index | Raster index | Topics index | Keywords index | Graphical index | Full index
ยฉ 2003-2025 GRASS Development Team, GRASS GIS 8.4.2 Reference Manual
and that's the whole page, bestie!! ๐ฆ you made it to the end, main character behavior fr fr. this was GRASS 8.4.2, the r.mapcalc(1) manual page, last touched up on Saturday Jan 17 05:40:51 2026. go forth and do math on rasters, you gorgeous nerd ๐โจ
๐ฆ where this page comes from
- fedora 44: grass 8.4.2-4.fc44 ยท GPL-2.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms