Grid operations
The grid operations module provides functions for processing and transforming gridded raster data, including resolution decimation and flow direction conversions.
Overview
Grid operations are essential for:
- Multi-resolution modeling: Coarsen high-resolution DEMs, flow direction, and accumulation grids
- Flow direction processing: Handle different flow direction notation systems (Grass
r.watershedvs ArcGIS) - Preprocessing: Prepare gridded data for hydrological modeling
All functions handle NaN values.
Flow direction notations
MOBIDICpy supports two flow direction notation systems. All diagrams below are shown in geographic orientation (north up).
Grass notation (1-8)
Standard GRASS r.watershed convention: codes 1-8 placed counter-clockwise starting
from NE.
To use this notation, the option raster_settings.flow_dir_type in the YAML configuration file must be set to “Grass”.
Arc notation (powers of 2)
Standard ESRI ArcGIS convention: powers of 2 placed clockwise starting from E.
To use this notation, the option raster_settings.flow_dir_type in the YAML configuration file must be set to “Arc”.
MOBIDIC notation (1-8)
The flow directions, either in Grass or Arc notation, are then internally converted to MOBIDIC’s D8 encoding as follows:
Technical details
Degradation algorithm
- Divides the input grid into blocks of size
factor × factor - For regular rasters: computes mean of valid cells in each block
- For flow direction: finds the cell with maximum flow accumulation in each block, determines the dominant flow direction
- Applies
min_valid_fractionthreshold to avoid blocks with too few valid cells
Flow direction degradation
The algorithm preserves drainage patterns by:
- Finding the fine cell with maximum flow accumulation in each coarse block
- Determining which coarse neighbor the drainage flows to
- Assigning the appropriate flow direction code
- Normalizing flow accumulation by
factor × factorto maintain consistent scaling
Notes
- All functions return new arrays and transforms without modifying inputs
- NaN values are properly propagated and excluded from calculations
- Flow direction values must be in the valid range for the specified notation
- Invalid flow direction values (e.g., not in Grass 1-8 or Arc powers-of-2) are converted to NaN
Functions
Resolution decimation
mobidic.preprocessing.grid_operations.decimate_raster(data, factor, min_valid_fraction=0.125)
Coarsen raster resolution by aggregating cells.
Aggregates a fine-resolution grid into a coarser grid by averaging values within each block of size factor x factor. Blocks with too few valid cells (less than min_valid_fraction) are marked as NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
2D numpy array with raster values (NaN for nodata). |
required |
factor
|
int
|
Decimation factor (e.g., 2 means 2x2 blocks -> 1 cell). |
required |
min_valid_fraction
|
float
|
Minimum fraction of valid cells required in each block to compute the mean. Default is 0.125 (1/8 of cells). |
0.125
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Decimated 2D numpy array with shape (floor(nr/factor), floor(nc/factor)). |
Examples:
>>> import numpy as np
>>> data = np.random.rand(100, 100)
>>> decimated = decimate_raster(data, factor=2)
>>> decimated.shape
(50, 50)
Source code in mobidic/preprocessing/grid_operations.py
mobidic.preprocessing.grid_operations.decimate_flow_direction(flow_dir, flow_acc, factor, min_valid_fraction=0.125)
Coarsen flow direction and flow accumulation grids.
Aggregates fine-resolution flow direction and flow accumulation grids into coarser grids. For each coarse cell, identifies the fine cell with maximum flow accumulation and determines the coarse flow direction based on where that cell drains to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flow_dir
|
ndarray
|
2D numpy array with flow directions (1-8 notation, NaN for nodata). |
required |
flow_acc
|
ndarray
|
2D numpy array with flow accumulation values (NaN for nodata). |
required |
factor
|
int
|
Decimation factor (e.g., 2 means 2x2 blocks -> 1 cell). |
required |
min_valid_fraction
|
float
|
Minimum fraction of valid cells required in each block. Default is 0.125 (1/8 of cells). |
0.125
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Tuple of (decimated_flow_dir, decimated_flow_acc) as 2D numpy arrays. |
ndarray
|
Flow accumulation is normalized by factor **2 to account for cell size change. |
Notes
This function operates on flow_dir BEFORE conversion to MOBIDIC notation, so input is expected in standard GRASS r.watershed 1-8 notation: 1=NE, 2=N, 3=NW, 4=W, 5=SW, 6=S, 7=SE, 8=E
Examples:
>>> flow_dir = np.array([[2, 2], [2, 2]]) # All cells flow north (Grass code 2)
>>> flow_acc = np.array([[1, 1], [3, 4]]) # Different accumulation
>>> dec_dir, dec_acc = decimate_flow_direction(flow_dir, flow_acc, factor=2)
Source code in mobidic/preprocessing/grid_operations.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | |
Flow direction conversion
mobidic.preprocessing.grid_operations.convert_to_mobidic_notation(flow_dir, from_notation='Grass')
Convert flow direction from Grass or Arc notation to MOBIDIC notation.
Translates standard GRASS r.watershed (1-8) or ESRI ArcGIS (powers of 2) flow direction codes to MOBIDIC’s internal D8 encoding. The renumbering is direction-preserving (each input code maps to the MOBIDIC code with the same physical compass direction). The mapping matches MATLAB’s buildgis_mysql_include.m: GRASS: AI=[1 2 3 4 5 6 7 8]; MD=[5 6 7 8 1 2 3 4]; ArcGIS: AI=[1 2 4 8 16 32 64 128]; MD=[4 3 2 1 8 7 6 5];
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flow_dir
|
ndarray
|
2D numpy array with flow directions (NaN for nodata). |
required |
from_notation
|
Literal['Grass', 'Arc']
|
Source notation (‘Grass’ for 1-8 or ‘Arc’ for power-of-2). Default is ‘Grass’. |
'Grass'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Flow direction array converted to MOBIDIC notation (1-8). |
Notes
Standard GRASS r.watershed convention (1-8, CCW from NE; north up):
3 2 1 1 = NE 5 = SW
4 . 8 2 = N 6 = S
5 6 7 3 = NW 7 = SE
4 = W 8 = E
Standard ESRI ArcGIS convention (powers of 2, CW from E; north up):
32 64 128 1 = E 16 = W
16 . 1 2 = SE 32 = NW
8 4 2 4 = S 64 = N
8 = SW 128 = NE
MOBIDIC convention (1-8, CCW from SW; north up):
7 6 5 1 = SW 5 = NE
8 . 4 2 = S 6 = N
1 2 3 3 = SE 7 = NW
4 = E 8 = W
Direction-preserving mapping: GRASS -> MOBIDIC: 1->5, 2->6, 3->7, 4->8, 5->1, 6->2, 7->3, 8->4 ArcGIS -> MOBIDIC: 1->4, 2->3, 4->2, 8->1, 16->8, 32->7, 64->6, 128->5
Array orientation: rasters are loaded by grid_to_matrix() with np.flipud
so that increasing row index corresponds to moving NORTH. With that
orientation, MOBIDIC code k drains to the neighbor at offset
(di, dj) where di = [-1,-1,-1,0,1,1,1,0][k-1] and
dj = [-1,0,1,1,1,0,-1,-1][k-1]. For example, code 5 (NE) -> (+1, +1).
Examples:
>>> flow_dir_grass = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 1]])
>>> flow_dir_mobidic = convert_to_mobidic_notation(flow_dir_grass, 'Grass')
>>> flow_dir_mobidic
array([[5, 6, 7],
[8, 1, 2],
[3, 4, 5]])
Source code in mobidic/preprocessing/grid_operations.py
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | |
Examples
Coarsening a raster
from mobidic import grid_to_matrix, decimate_raster
import numpy as np
# Read high-resolution DTM (e.g., 10m)
dtm = grid_to_matrix("dtm_10m.tif")
# Degrade to 50m resolution (factor = 5)
dtm_decimated = decimate_raster(
data=dtm['data'],
factor=5,
min_valid_fraction=0.125 # Require at least 1/8 valid cells
)
print(f"Original shape: {dtm['data'].shape}")
print(f"Decimated shape: {dtm_decimated.shape}")
print(f"Original cellsize: {dtm['cellsize']} m")
print(f"New cellsize: {dtm['cellsize'] * 5} m")
Coarsening flow direction
from mobidic import grid_to_matrix, decimate_flow_direction
# Read flow direction and accumulation grids
flow_dir_data = grid_to_matrix("flow_direction.tif")
flow_acc_data = grid_to_matrix("flow_accumulation.tif")
# Degrade both grids together
flow_dir_coarse, flow_acc_coarse = decimate_flow_direction(
flow_dir=flow_dir_data['data'],
flow_acc=flow_acc_data['data'],
factor=5,
min_valid_fraction=0.5
)
print(f"Original shape: {flow_dir_data['data'].shape}")
print(f"Decimated shape: {flow_dir_coarse.shape}")
Converting flow direction notation
from mobidic import grid_to_matrix, convert_to_mobidic_notation
# Read flow direction in Grass notation (1-8)
flow_dir_grass = grid_to_matrix("flow_dir_grass.tif")
# Convert to MOBIDIC notation (used internally by the model)
flow_dir_mobidic = convert_to_mobidic_notation(
flow_dir=flow_dir_grass['data'],
from_notation="Grass"
)
# Or convert from Arc notation directly
flow_dir_arc = grid_to_matrix("flow_dir_arc.tif")
flow_dir_mobidic = convert_to_mobidic_notation(
flow_dir=flow_dir_arc['data'],
from_notation="Arc"
)