Raster Calculator
The Raster Calculator performs cell-level, or cell-by-cell, calculations on one or more raster datasets. You can write an expression manually, or describe your requirement in natural language and let AI draft a formula for you to review before running it. Mathematical operations, threshold filtering, reclassification, and multi-band composite calculations can all be processed in parallel at the cell level.
Main Capabilities
- Use multiple rasters and multiple bands in one expression.
- Support both single-statement and multi-statement code block modes.
- Provide built-in operators and common NumPy functions, including arithmetic, trigonometric, logical, and statistical functions.
- Use AI to generate, complete, or rewrite formulas from natural language.
- Automatically align inputs by resampling when input rasters have different spatial references or grids.
- Control NoData and numeric data types. The default output type is double-precision floating point, and the default NoData value is the maximum value representable by the current output type.
Workflow
Typical workflow:
- Add one or more input rasters.
- Write an expression directly, or use AI to generate a draft formula first.
- Set the output raster path and common output parameters, such as pixel type, NoData value, compression, and coordinate system.
- Run the tool to generate the output file.
AI Formula Writing
Writing formulas manually requires familiarity with the rules of the expression editor. You can also let AI generate a formula and then review it. AI is especially useful in scenarios such as:
- Quickly generating common formulas such as NDVI, index transformations, and weighted overlays.
- Writing multi-line reclassification logic with many conditions, where missing parentheses is easy.
- Rewriting an existing formula into a clearer multi-line form.
- Translating a business description into an executable raster calculation expression.
In general, AI can help you:
- Generate an initial formula from natural language.
- Rewrite a single-line formula as a more readable multi-line code block.
- Complete structures that are easy to mistype, such as
where(...)andlogical_and(...). - Convert business conditions into raster calculation logic.
You still need to manually confirm:
- Whether file names and band numbers are referenced correctly.
- Whether interval boundaries include equality signs as intended.
- Whether NoData is propagated or preserved according to your requirements.
- Whether the spatial resolution, extent, and coordinate system of multiple input rasters are appropriate.
- Whether the output value range matches the intended meaning, such as binary values, class values, or continuous values.
A practical approach is to ask AI to generate the formula first, and then ask it to "rewrite it as multiple lines with intermediate variable names." Complex logic becomes easier to review and less error-prone when you modify it later.
How To Use AI
- Open the tool: Open the Geoprocessing Toolbox > go to Raster Tools > Raster Calculation > open Raster Calculator.
- Prepare input rasters: Add the rasters used in this calculation to the current window. AI only generates formulas based on raster names and bands that already exist in the current window.
- Open the AI formula panel: Use the AI formula writing feature in the formula editing area.
- Enter your requirement: Clearly describe which rasters or bands to use, what calculation to perform, threshold values, how to handle null values, and what the output should represent.
- Review the AI result: Confirm the referenced file names, band numbers, boundary conditions, NoData handling, and output meaning.
- Run after review: Test with a small area or sample dataset first, then generate the full output after confirming the result.
Interacting With AI
Following a few conventions can help AI generate better formulas:
- Name the data directly, for example: "Use
image_a.tif.band4andimage_a.tif.band3to calculate NDVI." - Specify boundaries clearly, for example: "0 to 10 is class 1, 10 to 20 is class 2, and greater than 20 is class 3."
- Describe the null-value strategy, for example: "If any input is null, output null."
- Describe the output intent, for example: "I want a 0/1 mask" or "I want a 4-class classification result."
- If the generated formula does not match your intent, ask AI to revise it. Multi-turn conversation is supported.
AI Prompt Examples
The following examples are close to real work prompts and can be used as references.
Example 1: Ask AI To Write NDVI
You can say:
Use band4 and band2 of airborne_multiband_100m.tif to calculate NDVI.
AI will likely return a formula similar to this:
result = (airborne_multiband_100m.tif.band4 - airborne_multiband_100m.tif.band2) / (airborne_multiband_100m.tif.band4 + airborne_multiband_100m.tif.band2)
With null-value handling:
# Prompt
Use band4 and band2 of airborne_multiband_100m.tif to calculate NDVI. If the denominator is 0 or any input is null, output nan.
# Formula
nir = airborne_multiband_100m.tif.band4
red = airborne_multiband_100m.tif.band2
num = nir - red
den = nir + red
result = where(logical_or(den == 0, logical_or(isnan(nir), isnan(red))), nan, num / den)
This approach lets AI write the formula and also consider exceptional cases.
Note: Boolean functions do not apply default null-value handling. You must explicitly handle null values.
Example 2: Ask AI To Write Reclassification
Reclassify dem.tif into 4 classes: less than or equal to 100 is 1, greater than 100 and less than or equal to 500 is 2, greater than 500 and less than or equal to 1500 is 3, and all other values are 4. Keep null values as null.
Possible result:
result = where(isnan(dem.tif), nan, where(dem.tif <= 100, 1, where(logical_and(dem.tif > 100, dem.tif <= 500), 2, where(logical_and(dem.tif > 500, dem.tif <= 1500), 3, 4))))
This case is well suited for AI because nested where statements are easy to mistype manually.
Example 3: Ask AI To Write A Risk Mask
Generate a risk mask from slope.tif and rain.tif: assign 1 to cells where slope is greater than 15 and rainfall is greater than 500; assign 0 to all other cells. If any input is null, output null.
Possible result:
result = where(logical_or(isnan(slope.tif), isnan(rain.tif)), nan, where(logical_and(slope.tif > 15, rain.tif > 500), 1, 0))
Raster References And Band References
In the Raster Calculator, variables in an expression can point to an input raster or to a specific band of that raster.
- Reference scope
- Raster references are valid only for the current tool run.
- Names are case-sensitive.
- Raster reference (
Raster name)
- Use the file reference name in the input list, usually the file name, to reference a raster directly.
Example using a file name as the reference:
result = T50SKH_B02_100m.tif + T50SKH_B03_100m.tif
- Band reference (
RasterName.bandN)
- For multi-band rasters, use
raster_name.bandNto reference a specific band.Nstarts from 1. - For a single-band raster,
ais equivalent toa.band1.
Example:
nd = airborne_multiband_100m.tif.band4 - airborne_multiband_100m.tif.band2
Invalid examples:
c = a.band0
c = band1
Syntax Rules
Single-Statement Mode
Use an assignment form: output_variable = expression.
result = dem.tif * 0.001
Because the interface uses output file = by default, you can usually enter only the expression in the input box.
Code Block Mode
- Temporary variables and intermediate results are allowed.
- At least one statement must be an assignment, otherwise there is no output.
- If multiple assignment statements exist, the last assignment result is used as the final output.
- Variable names in a code block must be valid identifiers. Recommended style: lowercase letters, digits, and underscores, not starting with a digit.
- Intermediate variables can make complex logic easier to read.
# Define masks
m1 = (dem.tif >= 0) & (dem.tif <= 1610)
m2 = (dem.tif > 1610) & (dem.tif <= 2415)
m3 = (dem.tif > 2415) & (dem.tif <= 3468)
m4 = (dem.tif > 3468)
# Classify
result = (m1 * 1) + (m2 * 2) + (m3 * 3) + (m4 * 4)
Supported Operators
Arithmetic Operators
| Arithmetic operator | Name | Meaning | Example | Description |
|---|---|---|---|---|
| + | Addition | Add values | A + B | Add cell values |
| - | Subtraction | Subtract values | A - B | Subtract cell values |
| * | Multiplication | Multiply values | A * B | Multiply cell values |
| / | Division | True division | A / B | The result is floating point |
| // | Floor division | Round-down division | A // B | Commonly used for GIS classes |
| % | Modulo | Remainder | A % 5 | Periodic or class codes |
| ** | Power | Exponentiation | A ** 2 | Square or exponential model |
Comparison Operators
| Operator | Name | Meaning | Example | GIS meaning |
|---|---|---|---|---|
== | Equal to | Whether values are equal | A == B | Whether cell values are the same |
!= | Not equal to | Whether values are not equal | A != 0 | Non-NoData |
> | Greater than | Whether a value is greater | A > 10 | Threshold test |
< | Less than | Whether a value is smaller | A < 0 | Outlier test |
>= | Greater than or equal to | >= | A >= 100 | Lower-bound constraint |
<= | Less than or equal to | <= | A <= 15 | Upper-bound constraint |
Comparison results are cell-by-cell Boolean results. They can be used in later calculations. In arithmetic operations, Boolean values are automatically converted to 0 or 1.
# Boolean values in arithmetic: 1 if the condition is true, 0 otherwise
result = (dem.tif > 1000) * 1
Logical Operators (Cell By Cell)
The Raster Calculator follows the Python + NumPy syntax model. For logical operations on raster arrays, native Python logical operators and / or / not are not supported. Use NumPy-style cell-by-cell logical operations instead:
- Use bitwise operators
&,|, and~for logical AND, OR, and NOT. - Operators apply to each cell.
- Conditional expressions must use parentheses to make precedence explicit.
Logical operators are used to combine multiple conditions:
| Operator | Name | Meaning | Example | Description | Function equivalent |
|---|---|---|---|---|---|
| & | Logical AND | Both true | (a > 0) & (a < 10) | Cell-by-cell logical AND | logical_and(a, b) |
| | | Logical OR | Either true | (a > 0) | (a < 10) | Cell-by-cell logical OR | logical_or(a, b) |
| ~ | Logical NOT | Negation | ~(a > 0) | Cell-by-cell logical NOT | logical_not(a) |
| None | Element-wise XOR | Exclusive OR | Element-wise XOR | logical_xor(a, b) |
Important: always use parentheses when combining conditions.
risk = (slope.tif > 15) * 0.4 + (rain.tif > 100) * 0.6
mask = (a.tif > 0) & (a.tif < 10)
Operator Precedence (High To Low)
The tool follows common Python and mathematical precedence rules. When writing complex conditions, use parentheses to make your intent clear:
()**- Unary
+x,-x,~x *,/,//,%+,-- Bit shift
<<,>> &,^,|- Comparisons
==,!=,<,<=,>,>= - Assignment
=
NoData And Numeric Type Rules
- If any operand contains NoData, the result is NoData.
- The default output numeric type is
double(Float64) to reduce precision loss. - The default NoData value is the maximum value representable by the current output type.
Recommendations:
- If input rasters use inconsistent NoData definitions, first standardize NoData with tools related to invalid values to reduce unexpected propagation.
- If you want to treat missing values as 0 or as a constant, explicitly write conditional logic, usually with
where.
Spatial Consistency And Automatic Resampling
Multiple rasters must be spatially identical for cell-by-cell calculation, including CRS, cell size, grid alignment, and extent.
When input rasters are inconsistent, the tool automatically aligns them before calculation. Core rules:
- The first raster in the input list is used as the spatial reference raster, not the first raster that appears in the expression.
- Other rasters are automatically reprojected or resampled to the reference raster grid.
- Internal resampling uses the GDAL mechanism and defaults to nearest neighbor.
Spatial alignment logic:
Raster Calculator (this tool)
└── Automatically determine whether resampling is needed
└── Call Raster.resample_gdal_by_raster()
└── GDAL Warp / Reproject / Resample
└── GDAL built-in interpolation algorithm (nearest neighbor)
Additional notes:
- Calculation after alignment is performed only on the reference raster grid. Areas outside the reference extent are filled with NoData.
- If input rasters have different resolutions, the cell size of the reference raster is used.
Common Use Cases
NDVI (Single Band)
ndvi = (T50SKH_B08_100m.tif - T50SKH_B04_100m.tif) / (T50SKH_B08_100m.tif + T50SKH_B04_100m.tif)
Multi-Band Weighting
result = airborne_multiband_100m.tif.band1 * 0.5 + airborne_multiband_100m.tif.band2 * 0.5
Multi-Band Summation (Sigma)
result = Sigma([airborne_multiband_100m.tif.band1, airborne_multiband_100m.tif.band2, airborne_multiband_100m.tif.band3])
Maximum Of Three Rasters (Nested maximum)
Use the nested maximum function to get the maximum value from multiple rasters.
result = maximum(A.tif, maximum(B.tif, C.tif))
Conditional Mask And Extraction
mask = (slope.tif > 15) & (rain.tif > 100)
result = where(mask, dem.tif, 0)
Unit Conversion / Linear Scaling
# Example: meters to kilometers
result = dem.tif / 1000.0
Usage Tips
- When asking AI to write a formula for the first time, provide the full input raster names and band numbers.
- If the result is wrong, do not only say "it is wrong." Give specific corrections, such as "the class 2 boundary should include 2415" or "do not convert null values to 0."
- For classification tasks, review each class after AI generates the formula to confirm that intervals are continuous, non-overlapping, and complete.
- For production data, first validate the result layer on a small area, then run the full dataset.
Reclassification (where Function)
Reclassification remaps raster cell values to new class values based on specific ranges. In the Python Raster Calculator, standard if statements cannot directly process arrays because of scalar logic limits. Use the where function to implement matrix-based parallel logic.
- Syntax:
where(condition, value_if_true, value_if_false). For multi-class classification, such as 4 classes, use nested form:where(condition1, value1, where(condition2, value2, value3)). - Input file:
"T50SKH_B02_100m.tif", a single-band raster dataset. - Calculation expression:
where(T50SKH_B02_100m.tif <= 1610, 1, where(T50SKH_B02_100m.tif <= 2415, 2, where(T50SKH_B02_100m.tif <= 3468, 3, 4))) - You can use multi-line statements to make the logic clearer.
# Step 1: Define class range variables to improve readability
class1 = T50SKH_B02_100m.tif <= 1610
class2 = T50SKH_B02_100m.tif <= 2415
class3 = T50SKH_B02_100m.tif <= 3468
# Step 2: Assign class values progressively with nested where statements
# Logic: if class1 is true, assign 1; otherwise continue checking class2, and so on
result = where(class1, 1, where(class2, 2, where(class3, 3, 4)))
Reclassification (Logical And Comparison Operations)
Reclassification remaps raster cell values to new class values based on specific ranges. In the Python Raster Calculator, use comparison operators, such as > and <=, and logical operators, such as logical_and, to implement reclassification.
- Comparison operators:
greater_equal(>=),less_equal(<=),greater(>), andless(<). You can use the symbols directly in expressions. - Logical operators:
&,|, and~represent logicallogical_and(AND),logical_or(OR), andlogical_not(NOT). Use them to combine multiple interval conditions. - Input file:
"T50SKH_B02_100m.tif", a single-band raster dataset. - Calculation expression 1:
(T50SKH_B02_100m.tif <= 1610) * 1 + ((T50SKH_B02_100m.tif > 1610) & (T50SKH_B02_100m.tif <= 2415)) * 2 + ((T50SKH_B02_100m.tif > 2415) & (T50SKH_B02_100m.tif <= 3468)) * 3 + (T50SKH_B02_100m.tif > 3468) * 4 - Calculation expression 2:
(T50SKH_B02_100m.tif <= 1610) * 1 + (T50SKH_B02_100m.tif > 1610) * (T50SKH_B02_100m.tif <= 2415) * 2 + (T50SKH_B02_100m.tif > 2415) * (T50SKH_B02_100m.tif <= 3468) * 3 + (T50SKH_B02_100m.tif > 3468) * 4 - Explanation: This expression uses the fact that Boolean values are automatically converted to 0 or 1 in arithmetic operations. Multiplication locks each interval with logical AND, and addition combines mutually exclusive class results to complete all reclassification in one line. For example, when
T50SKH_B02_100m.tif <= 1610is true, the expression becomes1 * 1, and the result is 1. When it is false, the expression becomes0 * 1, and the result is 0. - You can use multi-line statements to make the logic clearer.
# 1. Use comparison operators to define Boolean masks for each interval
# Range 0 - 1610.47 -> class 1
m1 = (T50SKH_B02_100m.tif >= 0) & (T50SKH_B02_100m.tif <= 1610)
# Range 1610.47 - 2415.71 -> class 2
# Use the logical_and function or the & symbol
m2 = logical_and(T50SKH_B02_100m.tif > 1610, T50SKH_B02_100m.tif <= 2415)
# Range 2415.71 - 3468.71 -> class 3
m3 = (T50SKH_B02_100m.tif > 2415) & (T50SKH_B02_100m.tif <= 3468)
# Range 3468.71 - 15795 -> class 4
m4 = (T50SKH_B02_100m.tif > 3468)
# 2. Multiply Boolean results by class values and sum them to get the final result
result = (m1 * 1) + (m2 * 2) + (m3 * 3) + (m4 * 4)
Common Errors
c a + b # Missing equals sign
c = # Missing expression
c = a / 0 # Division by zero
mask = a > 0 and b > 0 # Error: and/or/not are not cell-by-cell operators