regionmask
¶
Classes:
-
RegionMask–The RegionMask object represents a given region and exposes methods allowing
RegionMask
¶
The RegionMask object represents a given region and exposes methods allowing for easy manipulation of geospatial data around that region.
RegionMask objects are defined by providing a polygon (either via a vector file, an ogr.Geometry, or a Well-Known-Text (WKT) string), a projection system to work in, and an extent and pixel resolution to create a matrix mask (i.e. boolean values) of.
- The extent of the generated mask matrix is the tightest fit around the region in units of the pixel resolution. However, the extent can be defined explicitly if desired
- The region can be manipulated as a vector polygon via the ".geometry" attribute, which exposes the geometry as an ogr.Geometry. To incorporate this into other vector-handeling libraries it is suggested to use the ".ExportToWkt()" method available via OGR.
- The region can be manipulated as a raster matrix via the ".mask" attribute which exposes the mask as a boolean numpy.ndarray
- Any raster source can be easily warped onto the region-mask's extent, projection, and resolution via the ".warp" method
- Any vector source can be rasterized onto the region-mask's extent, projection, and resolution via the ".rasterize" method
- The default mask set-up is defined by the constant members: DEFAULT_SRS, DEFAULT_RES, and DEFAULT_PAD
Initializers:
-
RegionMask(...)
- This is not the preferred way
-
RegionMask.fromVector( ... )
-
RegionMask.fromVectorFeature( ... )
-
RegionMask.fromGeom( ... )
-
RegionMask.fromMask( ... )
-
RegionMask.load( ... )
- This function tries to determine which of the other initializers should be used based off the input
The default constructor for RegionMask objects. Creates a RegionMask directly from a matrix mask and a given extent (and optionally a geometry). Pixel resolution is calculated in accordance with the shape of the mask mask and the provided extent.
- Generally one should use the '.load' or else one of the '.fromXXX' methods to create RegionMasks
Parameters:
-
(extent¶Extent object) –The geospatial context of the region mask * The extent must fit the given pixel sizes * All computations using the RegionMask will be evaluated within this spatial context
-
(pixelRes¶float or tuple) –The RegionMask's native pixel size(s) * If float : A pixel size to apply to both the X and Y dimension * If (float float) : An X-dimension and Y-dimension pixel size * All computations using the RegionMask will generate results in reference to these pixel sizes (i.e. either at this resolution or at some scaling of this resolution)
-
(mask¶numpy - ndarray, default:None) –A mask over the context area defining which pixel as inside the region and which are outside * Must be a 2-Dimensional bool-matrix describing the region, where: - 0/False -> "not in the region" - 1/True -> "Inside the region" * Either a mask or a geometry must be given, but not both
-
(geom¶ogr - Geomertry, default:None) –A geometric representation of the RegionMask's region * Either a mask or a geometry must be given, but not both
-
(attributes¶dict, default:None) –Keyword attributes and values to carry along with the RegionMask
Methods:
-
applyMask–Shortcut to apply the RegionMask's mask to an array. Mainly intended
-
buildGeometry–Explicitly build the RegionMask's geometry.
-
buildMask–Explicitly build the RegionMask's mask matrix.
-
contoursFromMask–Convenience wrapper for geokit.raster.contours which automatically
-
contoursFromMatrix–Convenience wrapper for geokit.raster.contours which automatically
-
contoursFromRaster–Convenience wrapper for geokit.raster.contours which automatically
-
createRaster–Convenience wrapper for geokit.raster.createRaster which sets 'srs',
-
drawGeoms–Convenience wrapper around geokit.geom.drawGeoms which plots geometries
-
drawImage–Convenience wrapper around geokit.util.drawImage which plots matrix data
-
drawMask–Convenience wrapper around geokit.util.drawImage which plots the
-
drawRaster–Convenience wrapper around geokit.raster.drawRaster which plots a raster
-
drawSelf–Convenience wrapper around geokit.geom.drawGeoms which plots the
-
extractFeatures–Convenience wrapper for geokit.vector.extractFeatures() by setting the
-
fromGeom–Make a RasterMask from a given geometry.
-
fromMask–Make a RegionMask directly from a mask matrix and extent.
-
fromVector–Make a RasterMask from a given vector source.
-
indicateFeatures–Indicates the RegionMask pixels which are found within the features (or
-
indicateGeoms–Convenience wrapper to indicate values found within a geometry (or a
-
indicateValueToGeoms–TODO: UPDATE ME.
-
indicateValues–Indicates those pixels in the RegionMask which correspond to a particular
-
load–Tries to initialize and return a RegionMask in the most appropriate way.
-
mutateRaster–Convenience wrapper for geokit.vector.mutateRaster which automatically
-
mutateVector–Convenience wrapper for geokit.vector.mutateVector which automatically
-
polygonizeMask–Convenience wrapper for geokit.geom.polygonizeMask which automatically
-
polygonizeMatrix–Convenience wrapper for geokit.geom.polygonizeMatrix which automatically
-
rasterize–Convenience wrapper for geokit.vector.rasterize() which automatically
-
subRegions–Generate a number of sub regions on a grid which combine into the total
-
subTiles–Generates tile Extents at a given zoom level which encompass the invoking Regionmask.
-
warp–Convenience wrapper for geokit.raster.warp() which automatically sets
Attributes:
-
geometry–Fetches a clone of the RegionMask's geometry as an OGR Geometry object.
-
mask–The RegionMask's mask array as an 2-dimensional boolean numpy array.
-
pixelRes–The RegionMask's pixel size.
-
vector–Returns a vector saved in memory which is built only once.
-
vectorPath–Returns a path to a vector path on disc which is built only once.
Source code in geokit/core/regionmask.py
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 | |
geometry
property
¶
Fetches a clone of the RegionMask's geometry as an OGR Geometry object.
- If a geometry was not provided when the RegionMask was initialized, then one will be generated from the RegionMask's mask matrix in the RegionMask's extent
- The geometry can always be deleted and rebuild using the RegionMask.rebuildGeometry() function
mask
property
¶
The RegionMask's mask array as an 2-dimensional boolean numpy array.
- If no mask was given at the time of the RegionMask's creation, then a mask will be generated on first access to the 'mask' property
- The mask can be rebuilt in a customized way using the RegionMask.buildMask() function
pixelRes
property
¶
The RegionMask's pixel size.
!!Only available when pixelWidth equals pixelHeight!!
applyMask
¶
Shortcut to apply the RegionMask's mask to an array. Mainly intended for internal use.
-
When the passed matrix does not have the same extents of the given matrix, it is assumed that the RegionMask's mask needs to be scaled so that the matrix dimensions match
-
The RM's mask can only be scaled UP, and the given matrix's dimensions must be multiples of the mask's dimensions
Parameters:
-
(mat¶ndarray) –The matrix to apply the mask to * Must have dimensions equal, or are multiples of, the mask's
-
(noData¶float, default:0) –The no-data value to set into matrix's values which are not within the region
Returns:
-
ndarray–
Source code in geokit/core/regionmask.py
buildGeometry
¶
Explicitly build the RegionMask's geometry.
Source code in geokit/core/regionmask.py
buildMask
¶
Explicitly build the RegionMask's mask matrix.
- The 'width' and 'height' attributes for the RegionMask are also set when this function is called
- All kwargs are passed on to a call to geokit.vector.rasterize()
Source code in geokit/core/regionmask.py
contoursFromMask
¶
contoursFromMask(
mask,
truthThreshold=0.5,
trueAboveThreshold=True,
contoursKwargs={},
createRasterKwargs={},
)
Convenience wrapper for geokit.raster.contours which automatically creates a raster for the given mask (which is assumed to match the domain of the RegionMask), and extracts the geometries which are indicated in the mask as "True".
Parameters:
-
(mask¶matrix_like) –The mask which will be turned into a geometry set * Must be 2 dimensional
-
(truthThreshold¶[float], default:0.5) –The value which separates "True" from "False" values * Values are True when they are above the threshold unless trueAboveThreshold is set as False
-
–trueAboveThreshold¶If true, then pixels with values above the threshold are identified as "True"
-
(contoursKwargs¶dict, default:{}) –Keyword arguments to pass on to the contours function * See geokit.raster.contours
-
(createRasterKwargs¶dict, default:{}) –Keyword arguments to pass on to the raster creation function * See geokit.RegionMask.createRaster
Returns:
-
DataFrame– -
With columns:–'geom' -> The contiguous-valued geometries 'ID' -> The associated contour edge for each object
Source code in geokit/core/regionmask.py
contoursFromMatrix
¶
contoursFromMatrix(
matrix,
contourEdges,
contoursKwargs={},
createRasterKwargs={},
)
Convenience wrapper for geokit.raster.contours which automatically creates a raster for the given matrix (which is assumed to match the domain of the RegionMask).
Parameters:
-
(matrix¶matrix_like) –The matrix which will be turned into a geometry set * Must be 2 dimensional
-
(contourEdges¶[float]) –The edges to search for within the raster dataset * This parameter can be set as "None", in which case an additional argument should be given to specify how the edges should be determined - See the documentation of "GDALContourGenerateEx" - Ex. "LEVEL_INTERVAL=10", contourEdges=None
-
(contoursKwargs¶dict, default:{}) –Keyword arguments to pass on to the contours function * See geokit.raster.contours
-
(createRasterKwargs¶dict, default:{}) –Keyword arguments to pass on to the raster creation function * See geokit.RegionMask.createRaster
Returns:
-
DataFrame– -
With columns:–'geom' -> The contiguous-valued geometries 'ID' -> The associated contour edge for each object
Source code in geokit/core/regionmask.py
contoursFromRaster
¶
contoursFromRaster(
raster,
contourEdges,
applyMask=True,
contoursKwargs={},
warpKwargs={},
)
Convenience wrapper for geokit.raster.contours which automatically warps a raster to the invoking RegioNmask.
NOTE:
- The raster is first warped to the RegionMask before the contours are determined. If this behavior is not desired, consider using the function Extent.contoursFromRaster
Parameters:
-
(raster¶The raster datasource to warp from) – -
(contourEdges¶[float]) –The edges to search for within the raster dataset * This parameter can be set as "None", in which case an additional argument should be given to specify how the edges should be determined - See the documentation of "GDALContourGenerateEx" - Ex. "LEVEL_INTERVAL=10", contourEdges=None
-
(contoursKwargs¶dict, default:{}) –Keyword arguments to pass on to the contours function * See geokit.raster.contours
-
(warpKwargs¶dict, default:{}) –Keyword arguments to pass on to the raster warp function * See geokit.RegionMask.warp
Returns:
-
DataFrame– -
With columns:–'geom' -> The contiguous-valued geometries 'ID' -> The associated contour edge for each object
Source code in geokit/core/regionmask.py
createRaster
¶
createRaster(output=None, resolutionDiv=1, **kwargs)
Convenience wrapper for geokit.raster.createRaster which sets 'srs', 'bounds', 'pixelWidth', and 'pixelHeight' inputs.
Parameters:
-
(output¶str; optional, default:None) –A path to an output file to write to
-
(resolutionDiv¶int, default:1) –The factor by which to divide the RegionMask's native resolution * This is useful if you need to represent very fine details
-
–**kwargs¶All other keywargs are passed on to geokit.raster.createRaster() * See below for argument descriptions
Returns:
-
* If 'output' is None: gdal.Dataset– -
* If 'output' is a string: None–
Source code in geokit/core/regionmask.py
drawGeoms
¶
Convenience wrapper around geokit.geom.drawGeoms which plots geometries which are then plotted within the context of the RegionMask.
- See geokit.geom.drawGeoms for more info on argument options
- Geometries are always plotted in the RegionMask's SRS
- Unless specified, x and y limits are set to the RegionMask's extent
- This only plays a role when generating a new axis
Source code in geokit/core/regionmask.py
drawImage
¶
Convenience wrapper around geokit.util.drawImage which plots matrix data which is assumed to match the boundaries of the RegionMask.
- See geokit.util.drawImage for more info on argument options
- Unless specified, the plotting extent is set to the RegionMask's extent
- This only plays a role when generating a new axis
Source code in geokit/core/regionmask.py
drawMask
¶
Convenience wrapper around geokit.util.drawImage which plots the RegionMask's mask over the RegionMask's context.
- See geokit.util.drawImage for more info on argument options
- Unless specified, the plotting extent is set to the RegionMask's extent
- This only plays a role when generating a new axis
Source code in geokit/core/regionmask.py
drawRaster
¶
Convenience wrapper around geokit.raster.drawRaster which plots a raster dataset within the context of the RegionMask.
- See geokit.raster.drawRaster for more info on argument options
- The raster is always warped to the RegionMask's SRS
- Unless specified, x and y limits are set to the RegionMask's extent
- This only plays a role when generating a new axis
Source code in geokit/core/regionmask.py
drawSelf
¶
Convenience wrapper around geokit.geom.drawGeoms which plots the RegionMask's geometry.
- See geokit.geom.drawGeoms for more info on argument options
- Geometry are always plotted in the RegionMask's SRS
- Unless specified, x and y limits are set to the RegionMask's extent
- This only plays a role when generating a new axis
Source code in geokit/core/regionmask.py
extractFeatures
¶
Convenience wrapper for geokit.vector.extractFeatures() by setting the 'geom' input to the RegionMask's geometry.
Parameters:
-
(source¶str) –The path to the vector file to load
-
–**kwargs¶All other keyword arguments are passed on to vector.extractFeatures()
Returns:
-
* If asPandas is True: pandas.DataFrame or pandas.Series– -
* If asPandas is False: generator–
Source code in geokit/core/regionmask.py
fromGeom
staticmethod
¶
fromGeom(
geom,
srs,
pixelRes=DEFAULT_RES,
start_raster=None,
extent=None,
padExtent=DEFAULT_PAD,
attributes=None,
**region_mask_key_worded_arugments,
) -> RegionMask
Make a RasterMask from a given geometry.
Parameters:
-
(geom¶ogr - Geomertry or str) –A geometric representation of the RegionMask's region * If a string is given, geokit.geom.convertWKT(geom, srs) is called to convert it to an ogr.Geometry
-
(pixelRes¶float or tuple, default:DEFAULT_RES) –The RegionMask's native pixel resolution(s) * If float : A pixel size to apply to both the X and Y dimension * If (float float) : An X-dimension and Y-dimension pixel size
-
(srs¶Anything acceptable to geokit.srs.loadSRS()) –The srs context of the generated RegionMask object * This srs is superseded by the srs in an explicitly defined extent
-
(extent¶Extent object, default:None) –The geospatial context of the generated region mask * The extent must fit the given pixel sizes
-
(padExtent¶float; optional, default:DEFAULT_PAD) –An amount by which to pad the extent before generating the RegionMask
-
(attributes¶dict, default:None) –Keyword attributes and values to carry along with the RegionMask
Returns:
Source code in geokit/core/regionmask.py
fromMask
staticmethod
¶
fromMask(extent, mask, attributes=None) -> RegionMask
Make a RegionMask directly from a mask matrix and extent.
Note:
Pixel sizes are calculated from the extent boundaries and mask dimensional sizes
Parameters:
-
(extent¶Extent object) –The geospatial context of the region mask * The extent must fit the given pixel sizes * All computations using the RegionMask will be evaluated within this spatial context
-
(mask¶numpy - ndarray) –A mask over the context area defining which pixel as inside the region and which are outside * Must be a 2-Dimensional bool-matrix describing the region, where: - 0/False -> "not in the region" - 1/True -> "Inside the region"
-
(attributes¶dict, default:None) –Keyword attributes and values to carry along with the RegionMask
Returns:
Source code in geokit/core/regionmask.py
fromVector
staticmethod
¶
fromVector(
source,
srs,
where=None,
geom=None,
start_raster=None,
pixelRes=DEFAULT_RES,
extent=None,
padExtent=DEFAULT_PAD,
limitOne=True,
**kwargs,
) -> RegionMask
Make a RasterMask from a given vector source.
Note:
Be careful when creating a RegionMask over a large area (such as a country)! Using the default pixel size for a large area (such as a country) can easily consume your system's memory
Parameters:
-
(source¶Anything acceptable by loadVector()) –The vector data source to read from
-
(where¶str, int; optional, default:None) –If string -> An SQL-like where statement to apply to the source If int -> The feature's ID within the dataset * Feature attribute name do not need quotes * String values should be wrapped in 'single quotes' Example: If the source vector has a string attribute called "ISO" and a integer attribute called "POP", you could use....
where = "ISO='DEU' AND POP>1000" -
(geom¶ogr.Geometry; optional, default:None) –The geometry to search with * All features are extracted which touch this geometry
-
(pixelRes¶float or tuple, default:DEFAULT_RES) –The RegionMask's native pixel resolution(s) * If float : A pixel size to apply to both the X and Y dimension * If (float float) : An X-dimension and Y-dimension pixel size
-
(srs¶Anything acceptable to geokit.srs.loadSRS()) –The srs context of the generated RegionMask object * This srs is superseded by the srs in an explicitly defined extent
-
(extent¶Extent object, default:None) –The geospatial context of the generated region mask * The extent must fit the given pixel sizes * If not specified, the entire extent of the vector file is assumed
-
(padExtent¶float; optional, default:DEFAULT_PAD) –An amount by which to pad the extent before generating the RegionMask
-
(limitOne¶bool; optional, default:True) –Whether or not to allow more than one feature to be extracted
Returns:
Source code in geokit/core/regionmask.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | |
indicateFeatures
¶
indicateFeatures(
source: load_vector_input,
where: str | None = None,
buffer: numeric | None = None,
bufferMethod: Literal[
"geom", "area", "contour"
] = "geom",
resolutionDiv: int = 1,
forceMaskShape: bool = False,
applyMask: bool = True,
noData: numeric = 0,
preBufferSimplification: numeric | None = None,
multiProcess: bool = True,
**kwargs,
)
Indicates the RegionMask pixels which are found within the features (or a subset of the features) contained in a given vector datasource.
- A Rasterization is performed from the input data set to the RegionMask's mask. -See geokit.vector.rasterize or, more specifically gdal.RasterizeOptions kwargs for more info on how to control the rasterization step
Parameters:
-
(source¶str or Dataset) –The vector datasource to indicate from
-
(where¶str; optional, default:None) –An SQL-style filtering string * Can be used to filter the input source according to their attributes * For tips, see "http://www.gdal.org/ogr_sql.html" Ex: where="eye_color='Green' AND IQ>90"
-
(buffer¶float; optional, default:None) –A buffer region to add around the indicated pixels * Units are in the RegionMask's srs
-
(bufferMethod¶str; optional, default:'geom') –An indicator determining the method to use when buffering * Options are: 'geom', 'area', and 'contour' * If 'geom', the function will attempt to grow each of the geometries directly using the ogr library - This can fail sometimes when the geometries are particularly complex or if some of the geometries are not valid (as in, they have self-intersections) * If 'area', the function will first rasterize the raw geometries and will then apply the buffer to the indicated pixels - This is the safer option although is not as accurate as the 'geom' option since it does not capture the exact edges of the geometries - This method can be made more accurate by increasing the 'resolutionDiv' input * If 'contour', the function will still rasterize the raw geometries, but will then create geometries via mask contours (not the explicit pixel edges) - This option will recreate geometries which are more similar to the original geometries compared to the 'area' method - This method can be made more accurate by increasing the 'resolutionDiv' input
-
(resolutionDiv¶int; optional, default:1) –The factor by which to divide the RegionMask's native resolution * This is useful if you need to represent very fine details
-
(forceMaskShape¶bool; optional, default:False) –If True, forces the returned matrix to have the same dimension as the RegionMask's mask regardless of the 'resolutionDiv' argument
-
(applyMask¶bool; optional, default:True) –When True, the RegionMask's mask will be applied to the outputData as described by RegionMask.applyMask
-
(noData¶numeric, default:0) –The noData value to use when applying the mask
-
(preBufferSimplification¶numeric | None, default:None) –If given, then geometries will be simplified (using ogr.Geometry.Simplify) using the specified value before being buffered - Using this can drastically decrease the time it takes to perform the buffering procedure, but can decrease accuracy if it is too high
-
(multiProcess¶bool, default:True) –If True, multiple parallel processes will be spawned within the function to improve RAM efficiency, else it will fall back on linear execution. By default True.
-
–kwargs¶- Most notably: 'allTouched'
Returns:
-
ndarray–
Source code in geokit/core/regionmask.py
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 | |
indicateGeoms
¶
Convenience wrapper to indicate values found within a geometry (or a list of geometries).
- Simply creates a new vector source from the given geometry and then calls RegionMask.indicateFeatures
- All keywords are passed on to RegionMask.indicateFeatures
Source code in geokit/core/regionmask.py
indicateValueToGeoms
¶
TODO: UPDATE ME.
Source code in geokit/core/regionmask.py
indicateValues
¶
indicateValues(
source: load_raster_input,
value: numeric | tuple | list | str,
buffer: numeric | None = None,
resolutionDiv: int = 1,
forceMaskShape: bool = False,
applyMask: bool = True,
noData: numeric | None = None,
resampleAlg: Literal[
"near",
"bilinear",
"cubic",
"average",
"mode",
"max",
"min",
] = "bilinear",
bufferMethod: Literal["area", "contour"] = "area",
preBufferSimplification=None,
warpDType: geokit_c_data_types_literal | None = None,
prunePatchSize: numeric = 0,
threshold: numeric = 0.5,
multiProcess: bool = True,
**kwargs,
)
Indicates those pixels in the RegionMask which correspond to a particular value, or range of values, from a given raster datasource.
Returns a matrix matching the RegionMask's mask dimensions wherein 0 means the pixels is not included in the indicated set, and 1 meaning the pixel is included in the indicated set. Intermediate values are also possible. This results from a scenario when the datasource's resolution does not line up perfectly with the RegionMask's resolution and, as a result, a RegionMask pixel overlaps multiple datasource pixels which are not all indicated (or not-indicated).
- Value processing is performed BEFORE a warp takes place
- Output from the warp is clipped to values between 0 and 1
- If a boolean matrix is desired of the result, use "result > 0.5"
Parameters:
-
(source¶str or Dataset) –The raster datasource to indicate from
-
(value¶(numeric, tuple, iterable or str)) –The value, range, or set of values to indicate on * If float : The exact value to accept * If tuple : The inclusive range to accept. Given as (low,high) - Assumes exactly 2 values are present - If either value is "None", then the range is assumed to be unbounded on that side * If any other iterable : The list of exact values to accept * If str : The formatted set of elements to accept - Each element in the set is separated by a "," - Each element must be either a singular numeric value, or a range - A range element begins with either "[" or "(", and ends with either "]" or ")" and should have an '-' in between - "[" and "]" imply inclusivity - "(" and ")" imply exclusivity - Numbers on either side can be omitted, impling no limit on that side - Examples: - "[1-5]" -> Indicate values from 1 up to 5, inclusively - "[1-5)" -> Indicate values from 1 up to 5, but not including 5 - "(1-]" -> Indicate values above 1 (but not including 1) up to infinity - "[-5]" -> Indicate values from negative infinity up to and including 5 - "[-]" -> Indicate values from negative infinity to positive infinity (dont do this..) - All whitespaces will be ignored (so feel free to use them as you wish) - Example: - "[-2),[5-7),12,(22-26],29,33,[40-]" will indicate all of the following: - Everything below 2, but not including 2 - Values between 5 up to 7, but not including 7 - 12 - Values above 22 up to and including 26 - 29 - 33 - Everything above 40, including 40
-
(buffer¶float; optional, default:None) –A buffer region to add around the indicated pixels * Units are in the RegionMask's srs * The buffering occurs AFTER the indication and warping step and so it may not represent the original dataset exactly - Buffering can be made more accurate by increasing the 'resolutionDiv' input
-
(resolutionDiv¶int, default:1) –The factor by which to divide the RegionMask's native resolution * This is useful if you need to represent very fine details
-
(resampleAlg¶str; optional, default:'bilinear') –The resampling algorithm to use when warping values * Options are: 'near', 'bilinear', 'cubic', 'average', 'mode', 'max', 'min' * Knowing which option to use can have significant impacts! When indicating from a low resolution raster (relative to the region mask), then it is best to use one of 'near', 'bilinear', or 'cubic'. However, when indicating from a high resolution raster file (again, relative to the region mask) then one of 'average', 'mode', 'max', or 'min' is likely better.
-
(warpDType¶str or None; optional, default:None) –If given, this controls the raster datatype of the warped indication matrix. If not given, then a default datatype is assumed based off
resampleAlg:reampleAlg : assumed dtype
'near' : 'uint8''bilinear' : 'float32' 'cubic' : 'float32' 'average' : 'float32' 'mode' : 'uint8' 'max' : 'uint8' 'min' : 'uint8'
-
(forceMaskShape¶bool, default:False) –If True, forces the returned matrix to have the same dimension as the RegionMask's mask regardless of the 'resolutionDiv' argument
-
(applyMask¶bool, default:True) –When True, the RegionMask's mask will be applied to the outputData as described by RegionMask.applyMask
-
(noData¶numeric, default:None) –The noData value to use when applying the mask
-
–geomsFromContours¶If True, then geometries will be constructed from the function geokit.RegionMask.contoursFromMatrix, as opposed to using geokit.RegionMask.polygonizeMask. - This will result in simpler geometries which are easier to grow, but which do not strictly follow the edges of the indicated pixels
-
(bufferMethod¶str; optional, default:'area') –An indicator determining the method to use when buffereing * Options are: 'area' and 'contour' * If 'area', the function will first rasterize the raw geometries and will then apply the buffer to the indicated pixels - Uses geokit.RegionMask.polygonizeMask - This is the safer option although is not as accurate as the 'geom' option since it does not capture the exact edges of the geometries - This method can be made more accurate by increasing the 'resolutionDiv' input * If 'contour', the function will still rasterize the raw geometries, but will then create geometries via mask contours (not the explicit pixel edges) - Uses geokit.RegionMask.contoursFromMatrix - This option will recreate geometries which are more similar to the original geometries compared to the 'area' method - This method can be made more accurate by increasing the 'resolutionDiv' input
-
–preBufferSimplification¶If given, then geometries will be simplified (using ogr.Geometry.Simplify) using the specified value before being buffered - Using this can drastically decrease the time it takes to perform the buffering procedure, but can decrease accuracy if it is too high
-
(prunePatchSize¶numeric, default:0) –If given, then isolated non-indicated patches below the given size will be removed. The given value corresponds to the minimum area in the unit of the regionmask SRS that will not be removed. Defaults to 0, i.e. no patches will be removed. Note: This is applied to the geoms after buffer application and can deviate from the patch size after final rasterization.
-
(threshold¶numeric, default:0.5) –The cell value ABOVE which cells count as positively indicated, relevant for partial overlaps with buffer method 'area'. Defaults to 0.5.
-
(multiProcess¶bool, default:True) –If True, multiple parallel processes will be spawned within the function to improve RAM efficiency, else it will fall back on linear execution. By default True. Only works on Linux and will be deactivated on Windows and Mac.
-
–kwargs¶- Most notably: 'resampleAlg'
Returns:
-
ndarray–
Source code in geokit/core/regionmask.py
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 | |
load
staticmethod
¶
load(region, start_raster=None, **kwargs) -> RegionMask
Tries to initialize and return a RegionMask in the most appropriate way.
Note:
If 'region' input is... * Already a RegionMask, simply return it * A file path, use RegionMask.fromVector * An OGR Geometry object, assume is it to be loaded by RegionMask.fromGeom * A NumPy array, assume is it to be loaded by RegionMask.fromMask - An 'extent' input must also be given
Parameters:
-
(region¶Can be RegionMask, str, ogr.Geometry, numpy.ndarray) –The shape defining the region over which to build the RegionMask * See the note above
-
(where¶str, int; optional) –If string -> An SQL-like where statement to apply to the source If int -> The feature's ID within the dataset * Feature attribute name do not need quotes * String values should be wrapped in 'single quotes' Example: If the source vector has a string attribute called "ISO" and a integer attribute called "POP", you could use....
where = "ISO='DEU' AND POP>1000" -
(geom¶ogr.Geometry; optional) –The geometry to search with * All features are extracted which touch this geometry
-
(pixelRes¶float or tuple) –The RegionMask's native pixel resolution(s) * If float : A pixel size to apply to both the X and Y dimension * If (float float) : An X-dimension and Y-dimension pixel size
-
(srs¶Anything acceptable to geokit.srs.loadSRS()) –The srs context of the generated RegionMask object * This srs is superseded by the srs in an explicitly defined extent
-
(extent¶Extent object) –The geospatial context of the generated region mask * The extent must fit the given pixel sizes * If not specified, the entire extent of the vector file is assumed
-
(padExtent¶float; optional) –An amount by which to pad the extent before generating the RegionMask
Source code in geokit/core/regionmask.py
mutateRaster
¶
mutateRaster(
source: load_raster_input,
matchContext: bool = True,
warpArgs: dict | None = None,
applyMask: bool = True,
processor: Callable | None = None,
resampleAlg: Literal[
"near", "bilinear", "cubic", "average"
] = "bilinear",
**mutateArgs,
)
Convenience wrapper for geokit.vector.mutateRaster which automatically sets 'bounds'. It also warps the raster to the RegionMask's area and srs before mutating.
Note:
If this is called without any arguments except for a source, it serves to clip the raster source around the RegionMask, therefore performing the same function as RegionMask.warp(..., returnMatrix=False)
Parameters:
-
(source¶Anything acceptable to geokit.raster.loadRaster()) –The source to mutate
-
(matchContext¶bool; optional, default:True) –- If True, Warp to the RegionMask's boundaries, srs and pixel size before mutating
- If False, only warp to the RegionMask's boundaries, but keep its srs and resolution intact
-
(resampleAlg¶str; optional, default:'bilinear') –The resampling algorithm to use when warping values * Knowing which option to use can have significant impacts! * Options are: 'nearesampleAlg=resampleAlg, r', 'bilinear', 'cubic', 'average'
-
(warpArgs¶dict; optional, default:None) –Arguments to apply to the warping step * See geokit.raster.warp()
-
(processor¶Callable | None, default:None) –The function performing the mutation of the raster's data * The function will take single argument (a 2D numpy.ndarray) * The function must return a numpy.ndarray of the same size as the input * The return type must also be containable within a Float32 (int and boolean is okay) * See example in geokit.raster.mutateRaster for more info
-
(applyMask¶bool; optional, default:True) –When True, the RegionMask's mask will be applied to the outputData as described by RegionMask.applyMask
-
–**mutateArgs¶All other keyword arguments are passed to geokit.vector.mutateVector
Returns:
-
* If 'output' is None: gdal.Dataset– -
* If 'output' is a string: None–
Source code in geokit/core/regionmask.py
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 | |
mutateVector
¶
mutateVector(
source, matchContext=False, regionPad=0, **kwargs
)
Convenience wrapper for geokit.vector.mutateVector which automatically sets 'srs' and 'geom' inputs to the RegionMask's srs and geometry.
- The RegionMask's geometry is always used to select features within the source. If you need a broader scope, try using the RegionMask's extent's version of this function
Note:
If this is called without any arguments except for a source, it serves to clip the vector source around the RegionMask
Parameters:
-
(source¶Anything acceptable to geokit.vector.loadVector()) –The source to clip
-
(matchContext¶bool; optional, default:False) –- If True, transforms all geometries to the RegionMask's srs before mutating
- If False, only selects the geometries which touch the RegionMask
-
–regionPad¶Will buffer the regionmask geometry by a value (in the unit of the regionmask srs) before mutating the source vector onto it. Defaults to 0.
-
–**kwargs¶All other keyword arguments are passed to geokit.vector.mutateVector
Returns:
-
* If 'output' is None: gdal.Dataset– -
* If 'output' is a string: None–
Source code in geokit/core/regionmask.py
polygonizeMask
¶
Convenience wrapper for geokit.geom.polygonizeMask which automatically sets the 'bounds' and 'srs' inputs. The mask data is assumed to span the RegionMask exactly.
Each True-valued group of pixels will be converted to a geometry
Parameters:
-
(mask¶matrix_like) –The mask which will be turned into a geometry set * Must be 2 dimensional * Must be boolean type * True values are interpreted as 'in the geometry'
-
(flat¶bool, default:True) –If True, flattens the resulting geometries into a single geometry
-
(shrink¶bool, default:True) –If True, shrink all geoms by a tiny amount in order to avoid geometry overlapping issues * The total amount shrunk should be very very small * Generally this should be left as True unless it is ABSOLUTELY necessary to maintain the same area
Returns:
-
If 'flat' is True: ogr.Geometry– -
else([Geometry]) –
Source code in geokit/core/regionmask.py
polygonizeMatrix
¶
Convenience wrapper for geokit.geom.polygonizeMatrix which automatically sets the 'bounds' and 'srs' inputs. The matrix data is assumed to span the RegionMask exactly.
Each unique-valued group of pixels will be converted to a geometry
Parameters:
-
(matrix¶matrix_like) –The matrix which will be turned into a geometry set * Must be 2 dimensional * Must be integer or boolean type
-
(flat¶bool, default:False) –If True, flattens the resulting geometries which share a contiguous matrix value into a single geometry object
-
(shrink¶bool, default:True) –If True, shrink all geoms by a tiny amount in order to avoid geometry overlapping issues * The total amount shrunk should be very very small * Generally this should be left as True unless it is ABSOLUTELY necessary to maintain the same area
Returns:
-
pandas.DataFrame -> With columns:–'geom' -> The contiguous-valued geometries 'value' -> The value for each geometry
Source code in geokit/core/regionmask.py
rasterize
¶
rasterize(
source,
output=None,
resolutionDiv=1,
returnMatrix=True,
applyMask=True,
noData=None,
**kwargs,
)
Convenience wrapper for geokit.vector.rasterize() which automatically sets the 'srs', 'bounds', 'pixelWidth', and 'pixelHeight' inputs.
Note:
When creating an 'in memory' raster vs one which is saved to disk, a slightly different algorithm is used which can sometimes add an extra row of pixels. Be aware of this if you intend to compare value-matricies directly from rasters generated with this function.
Parameters:
-
(source¶str) –The path to the vector file to load
-
(output¶str; optional, default:None) –A path to an output file to write to
-
(resolutionDiv¶int; optional, default:1) –The factor by which to divide the RegionMask's native resolution * This is useful if you need to represent very fine details
-
(returnAsMatrix¶bool; optional) –When True, the resulting raster's matrix is return * Should have the same dimensions as the RegionMask's mask matrix
-
(applyMask¶bool; optional, default:True) –When True, the RegionMask's mask will be applied to the outputData as described by RegionMask.applyMask
-
(noData¶numeric; optional, default:None) –The noData value to use when applying the mask
-
–**kwargs¶All other keywargs are passed on to geokit.vector.rasterize()
Returns:
-
* If 'output' is None: gdal.Dataset– -
* If 'output' is a string: None–
Source code in geokit/core/regionmask.py
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 | |
subRegions
¶
Generate a number of sub regions on a grid which combine into the total RegionMask area.
Source code in geokit/core/regionmask.py
subTiles
¶
subTiles(zoom, checkIntersect=True, asGeom=False)
Generates tile Extents at a given zoom level which encompass the invoking Regionmask.
Parameters:
-
(zoom¶int) –The zoom level of the expected tile source
-
(checkIntersect¶bool, default:True) –If True, exclude tiles which do not intersect with the RegionMask's geometry
-
(asGeom¶bool, default:False) –If True, returns tuple of ogr.Geometries in stead of (xi,yi,zoom) tuples
Returns:
-
Generator of Geometries or (xi,yi,zoom) tuples–
Source code in geokit/core/regionmask.py
warp
¶
warp(
source,
output: str | None = None,
resolutionDiv=1,
returnMatrix=True,
applyMask=True,
noData=None,
resampleAlg="bilinear",
**kwargs,
) -> Dataset | ndarray | None
Convenience wrapper for geokit.raster.warp() which automatically sets 'srs', 'bounds', 'pixelWidth', and 'pixelHeight' inputs.
Note:
When creating an 'in memory' raster vs one which is saved to disk, a slightly different algorithm is used which can sometimes add an extra row of pixels. Be aware of this if you intend to compare value-matricies directly from rasters generated with this function.
Parameters:
-
(source¶str) –The path to the raster file to warp
-
(output¶str; optional, default:None) –A path to an output file to write to
-
(resampleAlg¶str; optional, default:'bilinear') –The resampling algorithm to use when warping values * Knowing which option to use can have significant impacts! * Options are: 'nearesampleAlg=resampleAlg, r', 'bilinear', 'cubic', 'average'
-
(resolutionDiv¶int, default:1) –The factor by which to divide the RegionMask's native resolution * This is useful if you need to represent very fine details
-
(returnAsMatrix¶bool) –When True, the resulting raster's matrix is return * Should have the same dimensions as the RegionMask's mask matrix
-
(applyMask¶bool, default:True) –When True, the RegionMask's mask will be applied to the outputData as described by RegionMask.applyMask
-
(noData¶numeric, default:None) –The noData value to use when applying the mask
-
–**kwargs¶All other keywargs are passed on to geokit.raster.warp()
Returns:
-
* If 'output' is None: gdal.Dataset– -
* If 'output' is a string: None–
Source code in geokit/core/regionmask.py
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 | |