raster_tools package
Contents
raster_tools package#
Subpackages#
Submodules#
raster_tools.batch module#
raster_tools.clipping module#
- raster_tools.clipping.clip(feature, data_raster, bounds=None)[source]#
Clip the data raster using the given feature.
- Parameters
feature (str, Vector) – The feature to clip with. If a string, this is interpreted as a path.
data_raster (str, Raster) – The data raster to be clipped. If a string, this is interpreted as a path.
bounds (tuple, list, array, optional) – The bounding box of the clip operation: (minx, miny, maxx, maxy). If not provided, the bounds are computed from the feature. This will trigger computation of the feature.
- Returns
The resulting clipped raster with dimensions that match the bounding box provided or the bounds of the feature.
- Return type
Raster
- raster_tools.clipping.clip_box(raster, bounds)[source]#
Clip the raster to the specified box.
- Parameters
raster (str, Raster) – The Raster or raster path string to clip.
bounds (tuple, list, array) – The bounding box of the clip operation: (minx, miny, maxx, maxy).
- Returns
The raster clipped to the given bounds.
- Return type
Raster
- raster_tools.clipping.envelope(feature, data_raster)[source]#
Clip the data raster using the bounds of the given feature.
This is the same as
clip()but the bounding box of the feature is used instead of the feature itself.- Parameters
feature (str, Vector) – The feature to erase with. If a string, this is interpreted as a path.
data_raster (str, Raster) – The data raster to be clipped. If a string, this is interpreted as a path.
- Returns
The resulting clipped raster with dimensions that match the bounding box of the feature.
- Return type
Raster
- raster_tools.clipping.erase(feature, data_raster, bounds=None)[source]#
Erase the data raster using the given feature. Inverse of
clip().- Parameters
feature (str, Vector) – The feature to erase with. If a string, this is interpreted as a path.
data_raster (str, Raster) – The data raster to be erased. If a string, this is interpreted as a path.
bounds (tuple, list, array, optional) – The bounding box of the clip operation: (minx, miny, maxx, maxy). If not provided, the bounds are computed from the feature. This will trigger computation of the feature.
- Returns
The resulting erased raster with dimensions that match the bounding box provided or the bounds of the feature. The data inside the feature is erased.
- Return type
Raster
- raster_tools.clipping.mask(feature, data_raster, invert=False)[source]#
Mask the data raster using the given feature.
Depending on invert, the area inside (
True) or outside (False) the feature is masked out. The default is to mask the area outside of the feature.- Parameters
feature (str, Vector) – The feature to mask with. If a string, this is interpreted as a path.
data_raster (str, Raster) – The data raster to be erased. If a string, this is interpreted as a path.
invert (bool, optional) – If
True, the mask is inverted and the area inside of the feature is set to masked out. DefaultFalse.
- Returns
The resulting masked raster with the same dimensions as the original data raster.
- Return type
Raster
raster_tools.creation module#
- raster_tools.creation.constant_raster(raster_template, value=1, bands=1)[source]#
Create a Raster filled with a contant value like a template raster.
This is a convenience function that wraps
full_like().- Parameters
raster_template (Raster, str) – Template raster used to define rows, columns, crs, resolution, etc
value (scalar, optional) – Value to fill result with. Default is 1.
bands (int, optional) – Number of bands desired for output. Default is 1.
- Returns
The resulting raster of constant values.
- Return type
Raster
- raster_tools.creation.empty_like(raster_template, bands=1, dtype=None)[source]#
Create a Raster filled with uninitialized data like a template raster.
- Parameters
raster_template (Raster, str) – Template raster used to define rows, columns, crs, resolution, etc
bands (int, optional) – Number of bands desired for output. Default is 1.
dtype (data-type, optional) – Overrides the result dtype.
- Returns
The resulting raster of uninitialized data.
- Return type
Raster
- raster_tools.creation.full_like(raster_template, value, bands=1, dtype=None)[source]#
Create a Raster filled with a contant value like a template raster.
- Parameters
raster_template (Raster, str) – Template raster used to define rows, columns, crs, resolution, etc
value (scalar) – Value to fill result with.
bands (int, optional) – Number of bands desired for output. Default is 1.
dtype (data-type, optional) – Overrides the result dtype.
- Returns
The resulting raster of constant values.
- Return type
Raster
- raster_tools.creation.ones_like(raster_template, bands=1, dtype=None)[source]#
Create a Raster filled with ones like a template raster.
- Parameters
raster_template (Raster, str) – Template raster used to define rows, columns, crs, resolution, etc
bands (int, optional) – Number of bands desired for output. Default is 1.
dtype (data-type, optional) – Overrides the result dtype.
- Returns
The resulting raster of ones.
- Return type
Raster
- raster_tools.creation.random_raster(raster_template, distribution='normal', bands=1, params=(1, 0.5))[source]#
Creates a Raster of random values based on the desired distribution.
This function uses dask.array.random to generate data. The default is a normal distribution with mean of 1 and standard deviation of 0.5.
- Parameters
raster_template (Raster, str) – A template raster used to define rows, columns, crs, resolution, etc.
distribution (str, optional) –
Random distribution type. Default is ‘normal’. See params parameter below for passing additional distribution parameters. Valid values are:
- ’binomial’
Binomial distribution. Uses two additional parameters: (n, p).
- ’normal’
Normal distribution. Uses two additional parameters: (mean, std). This is the default.
- ’poisson’
Poisson distribution. Uses one additional parameter.
- ’uniform’
Uniform distribution in the half-open interval [0, 1). Uses no additional.
- ’weibull’
Weibull distribution. Uses one additional parameter.
bands (int, optional) – Number of bands needed desired. Default is 1.
params (list of scalars, optional) – Additional parameters for generating the distribution. For example distribution=’normal’ and params=(1, 0.5) would result in a normal distribution with mean of 1 and standard deviation of 0.5. Default is
(1, 0.5).
- Returns
The resulting raster of random values pulled from the distribution.
- Return type
Raster
- raster_tools.creation.zeros_like(raster_template, bands=1, dtype=None)[source]#
Create a Raster filled with zeros like a template raster.
- Parameters
raster_template (Raster, str) – Template raster used to define rows, columns, crs, resolution, etc
bands (int, optional) – Number of bands desired for output. Default is 1.
dtype (data-type, optional) – Overrides the result dtype.
- Returns
The resulting raster of zreos.
- Return type
Raster
raster_tools.dask_utils module#
raster_tools.dtypes module#
raster_tools.focal module#
- raster_tools.focal.check_kernel(kernel)[source]#
Validate and return the focal kernel.
- Parameters
kernel (2D numpy.ndarray) – The kernel to validate. Errors are raised if it is not a numpy array, contains nan values, or is not 2D.
- Returns
The input kernel, if nothing was wrong with it.
- Return type
numpy.ndarray
- raster_tools.focal.convolve(raster, kernel, mode='constant', cval=0.0)[source]#
Convolve kernel with each band individually. Returns a new Raster.
This is the same as correlation but the kernel is rotated 180 degrees, e.g.
kernel = kernel[::-1, ::-1]. The kernel is applied to each band in isolation so the returned raster has the same shape as the original.- Parameters
raster (Raster) – The raster to convolve kernel with. Can be multibanded.
kernel (array_like) – 2D array of kernel weights
mode ({'reflect', 'constant', 'nearest', 'wrap'}, optional) –
Determines how the data is extended beyond its boundaries. The default is ‘constant’.
- ’reflect’ (d c b a | a b c d | d c b a)
The data pixels are reflected at the boundaries.
- ’constant’ (k k k k | a b c d | k k k k)
A constant value determined by cval is used to extend the data pixels.
- ’nearest’ (a a a a | a b c d | d d d d)
The data is extended using the boundary pixels.
- ’wrap’ (a b c d | a b c d | a b c d)
The data is extended by wrapping to the opposite side of the grid.
cval (scalar, optional) – Value used to fill when mode is ‘constant’. Default is 0.0.
- Returns
The resulting new Raster.
- Return type
Raster
- raster_tools.focal.correlate(raster, kernel, mode='constant', cval=0.0)[source]#
Cross-correlate kernel with each band individually. Returns a new Raster.
The kernel is applied to each band in isolation so returned raster has the same shape as the original.
- Parameters
raster (Raster or path str) – The raster to cross-correlate kernel with. Can be multibanded.
kernel (array_like) – 2D array of kernel weights
mode ({'reflect', 'constant', 'nearest', 'wrap'}, optional) –
Determines how the data is extended beyond its boundaries. The default is ‘constant’.
- ’reflect’ (d c b a | a b c d | d c b a)
The data pixels are reflected at the boundaries.
- ’constant’ (k k k k | a b c d | k k k k)
A constant value determined by cval is used to extend the data pixels.
- ’nearest’ (a a a a | a b c d | d d d d)
The data is extended using the boundary pixels.
- ’wrap’ (a b c d | a b c d | a b c d)
The data is extended by wrapping to the opposite side of the grid.
cval (scalar, optional) – Value used to fill when mode is ‘constant’. Default is 0.0.
- Returns
The resulting new Raster.
- Return type
Raster
- raster_tools.focal.focal(raster, focal_type, width_or_radius, height=None)[source]#
Applies a focal filter to raster bands individually.
The filter uses a window/footprint that is created using the width_or_radius and height parameters. The window can be a rectangle, circle or annulus.
- Parameters
raster (Raster or path str) – The raster to perform the focal operation on.
focal_type (str) –
Specifies the aggregation function to apply to the focal neighborhood at each pixel. Can be one of the following string values:
- ’min’
Finds the minimum value in the neighborhood.
- ’max’
Finds the maximum value in the neighborhood.
- ’mean’
Finds the mean of the neighborhood.
- ’median’
Finds the median of the neighborhood.
- ’mode’
Finds the mode of the neighborhood.
- ’sum’
Finds the sum of the neighborhood.
- ’std’
Finds the standard deviation of the neighborhood.
- ’var’
Finds the variance of the neighborhood.
- ’asm’
Angular second moment. Applies -sum(P(g)**2) where P(g) gives the probability of g within the neighborhood.
- ’entropy’
Calculates the entropy. Applies -sum(P(g) * log(P(g))). See ‘asm’ above.
- ’unique’
Calculates the number of unique values in the neighborhood.
width_or_radius (int or 2-tuple of ints) – If an int and height is None, specifies the radius of a circle window. If an int and height is also an int, specifies the width of a rectangle window. If a 2-tuple of ints, the values specify the inner and outer radii of an annulus window.
height (int or None) – If None (default), width_or_radius will be used to construct a circle or annulus window. If an int, specifies the height of a rectangle window.
- Returns
The resulting raster with focal filter applied to each band. The bands will have the same shape as the original Raster.
- Return type
Raster
- raster_tools.focal.get_focal_window(width_or_radius, height=None)[source]#
Get a rectangle, circle, or annulus focal window.
A rectangle window is simply a NxM grid of
Truevalues. A circle window is a grid with a centered circle ofTruevalues surrounded by False values. The circle extends to the edge of the grid. An annulus window is the same as a circle window but has a nested circle of False values inside the main circle.- Parameters
width_or_radius (int or 2-tuple of ints) – If an int and height is None, specifies the radius of a circle window. If an int and height is also an int, specifies the width of a rectangle window. If a 2-tuple of ints, the values specify the inner and outer radii of an annulus window.
height (int or None) – If None (default), width_or_radius will be used to construct a circle or annulus window. If an int, specifies the height of a rectangle window.
- Returns
window – A focal window containing bools with the specified pattern.
- Return type
ndarray
raster_tools.general module#
Description: general module used to perform common spatial analyses on Raster objects
- raster_tools.general.aggregate(raster, expand_cells, stype)[source]#
Creates a Raster of aggregated cell values for a new resolution.
The approach is based on ESRI’s aggregate and majority filter functions.
- Parameters
raster (Raster or path str) – Input Raster object or path string
expand_cells (2-tuple, list, array-like) – Tuple, array, or list of the number of cells to expand in y and x directions. The first element corresponds to the y dimension and the second to the x dimension.
stype (str) – Summarization type. Valid opition are mean, std, var, max, min, unique prod, median, mode, sum, unique, entropy, asm.
- Returns
The resulting raster of aggregated values.
- Return type
Raster
References
- raster_tools.general.band_concat(rasters)[source]#
Join a sequence of rasters along the band dimension.
- Parameters
rasters (sequence of Rasters and/or paths) – The rasters to concatenate. These can be a mix of Rasters and paths. All rasters must have the same shape in the x and y dimensions.
- Returns
The resulting concatenated Raster.
- Return type
Raster
- raster_tools.general.dilate(raster, size)[source]#
Perform dilation on a raster
Dilation increases the thickness of raster features. Features with higher values will cover features with lower values. At each cell, the miximum value within a window, defined by size, is stored in the output location. This is very similar to the max focal filter except that raster features are dilated (expanded) into null regions. Dilation is performed on each band separately.
- Parameters
raster (Raster or path str) – The raster to dilate
size (int or 2-tuple of ints) – The shape of the window to use when dilating. A Single int is interpreted as the size of a square window. A tuple of 2 ints is used as the dimensions of rectangular window. At least one value must be greater than 1. Values cannot be less than 1.
- Returns
The resulting raster with eroded features. This raster will have the same shape and meta data as the original
- Return type
Raster
See also
References
- raster_tools.general.erode(raster, size)[source]#
Perform erosion on a raster
Erosion increases the thickness of raster features. Features with higher values will cover features with lower values. At each cell, the miximum value within a window, defined by size, is stored in the output location. This is very similar to the max focal filter except that raster features are eroded (contracted) into null regions. Erosion is performed on each band separately.
- Parameters
raster (Raster or path str) – The raster to erode
size (int or 2-tuple of ints) – The shape of the window to use when eroding. A Single int is interpreted as the size of a square window. A tuple of 2 ints is used as the dimensions of rectangular window. At least one value must be greater than 1. Values cannot be less than 1.
- Returns
The resulting raster with eroded features. This raster will have the same shape and meta data as the original
- Return type
Raster
See also
References
- raster_tools.general.local_stats(raster, stype)[source]#
Creates a Raster of summarized values across bands.
The approach is based on ESRI’s local function.
- Parameters
raster (Raster or path str) – Input Raster object or path string
stype (str) – Summarization type. Valid opition are mean, std, var, max, min, maxband, minband, prod, sum, mode, median, unique, entropy, asm
- Returns
The resulting raster of values aggregated along the band dimension.
- Return type
Raster
References
- raster_tools.general.predict_model(raster, model)[source]#
Predict cell estimates from a model using raster band values as predictors.
Predictor bands correspond to the order of the predictor variables within the model. Outputs are raster surfaces with bands cell values depending on the type of model.
The function uses the model class’ predict method to estimate a new raster surface.
- Parameters
raster (Raster or path str) – Raster of predictor variables where the bands correspond to variables in the model (one band for each variable in the model).
model (object) – The model used to estimate new values. Must have a predict method that takes an xarray.DataArray object. The provided DataArray will have null cells marked with
NaN.
- Returns
The resulting raster of estmated values.
- Return type
Raster
- raster_tools.general.reclassify(raster, remapping, unmapped_to_null=False)[source]#
Reclassify the input raster values based on a mapping.
This function only works with integer type rasters.
- Parameters
raster (str, Raster) – The input raster to reclassify. Can be a path string or Raster object. The raster dtype must be integer.
remapping (str, dict) – Can be either a
dictor a path string. If adictis provided, the keys will be reclassified to the corresponding values. If a path string, it is treated as an ASCII remap file where each line looks likea:bandaandbare integers. All remap values (both from and to) must be integers.unmapped_to_null (bool, optional) – If
True, values not included in the mapping are instead mapped to the null value. Default isFalse.
- Returns
The remapped raster.
- Return type
Raster
- raster_tools.general.regions(raster, neighbors=4, unique_values=None)[source]#
Calculates the unique regions (patches) within a raster band.
The approach is based on ESRI’s region group calculation.
- Parameters
raster (Raster or path str) – The raster to perform the calculation on. All unique non zero values will be used to define unique regions.
neighbors (int, optional) – The neighborhood connectivity value. Valid values are 4 and 8. If 4, a rook pattern is used, e.g. the neighbors along the horizontal and vertical directions are used. if 8, then all of the 8 neighbors are used. Default is 4.
unique_values (array or list, optional) – Values that represent zones from which regions will be made. Values not included will be grouped together to form one large zone. If None, each unique value in the raster will be considered a zone and will be calculated up front.
- Returns
The resulting raster of unique regions values. The bands will have the same shape as the original Raster. The null value mask from the origial raster will be applied to the result.
- Return type
Raster
References
- raster_tools.general.remap_range(raster, mapping, inclusivity='left')[source]#
Remaps values based on a mapping or list of mappings.
Mappings are applied all at once with earlier mappings taking precedence.
- Parameters
raster (Raster or str) – Path string or Raster to perform remap on.
mapping (3-tuple of scalars or list of 3-tuples of scalars) – A tuple or list of tuples containing
(min, max, new_value)scalars. The mappiing(s) map values between the min and max to thenew_value. If mapping is a list and there are mappings that conflict or overlap, earlier mappings take precedence. inclusivity determines which sides of the range are inclusive and exclusive.inclusivity (str, optional) –
Determines whether to be inclusive or exclusive on either end of the range. Default is ‘left’.
- ’left’ [min, max)
Left (min) side is inclusive and right (max) side is exclusive.
- ’right’ (min, max]
Left (min) side is exclusive and right (max) side is inclusive.
- ’both’ [min, max]
Both sides are inclusive.
- ’none’ (min, max)
Both sides are exclusive.
- Returns
The resulting Raster.
- Return type
Raster
raster_tools.io module#
raster_tools.line_stats module#
- raster_tools.line_stats.length(features, like_rast, radius, weighting_field=None)[source]#
Calculate a raster where each cell is the net length of all features within a given radius.
This function returns a raster where each cell contains the sum of the lengths of all features that fall within a radius of the cell’s center. The features are clipped to the circular neighborhood before the length is computed. Optional weighting can be added with weighting_field.
- Parameters
features (Vector, str) – The line features to compute lengths from.
like_rast (Raster, str) – A raster to use as a reference grid and CRS. The output raster will be on the same grid.
radius (scalar) – The radius around each grid cell’s center to use. Features that fall within the radius are clipped to the resulting circle and their resulting lengths are summed. Additional weighting of the sum can be done using weighting_field. This should be in the same units as like_rast’s CRS.
weighting_field (str, optional) – If not
None, this selects a field in features to use as a weighting factor in the sum of lengths.
- Returns
The resulting raster where each cell contains the sum of all feature lengths in the circular neighborhood determined by radius.
- Return type
Raster
raster_tools.masking module#
raster_tools.raster module#
- class raster_tools.raster.BandwiseOperationAdapter(raster)[source]#
Bases:
numpy.lib.mixins.NDArrayOperatorsMixin
- class raster_tools.raster.Raster(raster, _fast_path=False)[source]#
Bases:
raster_tools.raster._RasterBaseAbstraction of georeferenced raster data with lazy function evaluation.
Raster is a wrapper around xarray Datasets and DataArrays. It takes advantage of xarray’s dask integration to allow lazy loading and evaluation. It allows a pipeline of operations on underlying raster sources to be built in a lazy fashion and then evaluated effiently. Most mathematical operations have been overloaded so operations such as
z = x - yandr = x**2are possible.All operations on a Raster return a new Raster.
- Parameters
raster (str, Raster, xarray.DataArray, xarray.Dataset, numpy.ndarray) – The raster source to use for this Raster. If raster is a string, it is treated like a path. If raster is a Raster, a copy is made and its raster source is used. If raster is an xarray DataArray, Dataset, or numpy array, it is used as the source. Dataset objects must contain ‘raster’ and ‘mask’ variables. The dimensions of these variables are assumed to be “band”, “y”, “x”, in that order. The ‘mask’ variable must have boolean dtype.
- property affine#
The affine transformation for the raster data.
This is an
affine.Affineobject.
- all(*args, **kwargs)#
Reduce the raster to a single dask value by applying all across all bands.
All arguments are ignored.
- any(*args, **kwargs)#
Reduce the raster to a single dask value by applying any across all bands.
All arguments are ignored.
- astype(dtype, warn_about_null_change=True)[source]#
Return a copy of the Raster cast to the specified type.
- Parameters
dtype (str, type, numpy.dtype) – The new type to cast the raster to. The null value will also be cast to this type. If the null value cannot be safely cast to the new type, a default null value for the given dtype is used. This will produce a warning unless warn_about_null_change is set to
False.warn_about_null_change (bool, optional) – Can be used to silence warnings. The default is to always warn about null value changes.
- Returns
The new dtype raster.
- Return type
- property bandwise#
Returns an adapter for band-wise operations on this raster
The returned adapter allows lists/arrays of values to be mapped to the raster’s bands for binary operations.
- property bounds#
Bounds tuple (minx, miny, maxx, maxy)
- burn_mask()[source]#
Fill null-masked cells with null value.
Use this as a way to return the underlying data to a known state. If dtype is boolean, the null cells are set to
Trueinstead of promoting to fit the null value.
- chunk(chunks)[source]#
Rechunk the underlying raster
- Parameters
chunks (tuple of int) – The chunk sizes for each dimension (“band”, “y”, “x”, in that order). Must be a 3-tuple.
- Returns
The rechunked raster
- Return type
- property crs#
The raster’s CRS.
This is a
rasterio.crs.CRSobject.
- property data#
The underlying dask array of data
- property dtype#
The dtype of the data.
- eval()[source]#
Compute any applied operations and return the result as new Raster.
Note that the unerlying sources will be loaded into memory for the computations and the result will be fixed in memory. The original Raster will be unaltered.
- get_bands(bands)[source]#
Retrieve the specified bands as a new Raster. Indexing starts at 1.
- Parameters
bands (int or sequence of ints) – The band or bands to be retrieved. A single band Raster is returned if bands is an int and a multiband Raster is returned if it is a sequence. The band numbers may be out of order and contain repeated elements. if bands is a sequence, the multiband raster’s bands will be in the order provided.
- Returns
The resulting raster composed of the specified bands in the order given.
- Return type
- index(x, y)[source]#
Return the (row, col) index of the pixel at (x, y).
- Parameters
x (float, array-like) – x value(s) in the raster’s CRS
y (float, array-like) – y value(s) in the raster’s CRS
- Returns
(row value(s), col value(s)). If the inputs where array-like, the output values will be arrays.
- Return type
tuple
- property mask#
The null value mask as a dask array.
- max(*args, **kwargs)#
Reduce the raster to a single dask value by applying max across all bands.
All arguments are ignored.
- mean(*args, **kwargs)#
Reduce the raster to a single dask value by applying mean across all bands.
All arguments are ignored.
- min(*args, **kwargs)#
Reduce the raster to a single dask value by applying min across all bands.
All arguments are ignored.
- property nbands#
The number of bands.
- property null_value#
The raster’s null value used to fill missing or invalid entries.
- plot(*args, **kwargs)[source]#
Plot the raster. Args and kwargs are passed to xarray’s plot function.
- prod(*args, **kwargs)#
Reduce the raster to a single dask value by applying prod across all bands.
All arguments are ignored.
- property pxrs#
- reclassify(remapping, unmapped_to_null=False)[source]#
Reclassify raster values based on a mapping.
The raster must have an integer type.
- Parameters
remapping (str, dict) – Can be either a
dictor a path string. If adictis provided, the keys will be reclassified to the corresponding values. If a path string, it is treated as an ASCII remap file where each line looks likea:bandaandbare integers. All remap values (both from and to) must be integers.unmapped_to_null (bool, optional) – If
True, values not included in the mapping are instead mapped to the null value. Default isFalse.
- Returns
The remapped raster.
- Return type
- remap_range(mapping, inclusivity='left')[source]#
Remaps values based on a mapping or list of mappings.
Mappings are applied all at once with earlier mappings taking precedence.
- Parameters
mapping (3-tuple of scalars or list of 3-tuples of scalars) – A tuple or list of tuples containing
(min, max, new_value)scalars. The mappiing(s) map values between the min and max to thenew_value. If mapping is a list and there are mappings that conflict or overlap, earlier mappings take precedence. inclusivity determines which sides of the range are inclusive and exclusive.inclusivity (str, optional) –
Determines whether to be inclusive or exclusive on either end of the range. Default is ‘left’.
- ’left’ [min, max)
Left (min) side is inclusive and right (max) side is exclusive.
- ’right’ (min, max]
Left (min) side is exclusive and right (max) side is inclusive.
- ’both’ [min, max]
Both sides are inclusive.
- ’none’ (min, max)
Both sides are exclusive.
- Returns
The resulting Raster.
- Return type
See also
- replace_null(value)[source]#
Replaces null values with value.
- Parameters
value (scalar) – The new value to replace null values with.
- Returns
The new resulting Raster. If value is a float and the raster dtype is int, the raster type will be promoted to float.
- Return type
- property resolution#
The x and y cell sizes as a tuple. Values are always positive.
- round(decimals=0)[source]#
Evenly round to the given number of decimals
- Parameters
decimals (int, optional) – The number of decimal places to round to. If negative, value specifies the number of positions to the left of the decimal point. Default is 0.
- Returns
Rounded raster.
- Return type
- save(path, no_data_value=None, **gdal_kwargs)[source]#
Compute the final raster and save it to the provided location.
- Parameters
path (str) – The target location to save the raster to.
no_data_value (scalar, optional) – A new null value to use when saving.
**gdal_kwargs (kwargs, optional) – Additional keyword arguments to to pass to rasterio and GDAL when writing the raster data.
- Returns
A raster pointing to the saved location.
- Return type
- set_crs(crs)[source]#
Set the CRS for the underlying data.
- Parameters
crs (object) – The desired CRS. This can be anything accepted by
rasterio.crs.CRS.from_user_input(i.e. 4326, “epsg:4326”, etc).- Returns
A new raster with the specified CRS.
- Return type
- set_null_value(value)[source]#
Sets or replaces the null value for the raster.
If there was previously no null value for the raster, one is set. If there was already a null value, then it is replaced. If the raster has an integer dtype and value is a float, the dtype will be promoted to a float dtype. If value is None, the null value is cleared. The raster data is not changed in this case.
- Parameters
value (scalar or None) – The new null value for the raster. If None, the resulting raster will have no null value, i.e. the null value is cleared.
- Returns
The new resulting Raster.
- Return type
- property shape#
The shape of the underlying raster. Dim 0 is the band dimension.
The shape will always be of the form
(B, Y, X)whereBis the band dimension,Yis the y dimension, andXis the x dimension.
- std(*args, **kwargs)#
Reduce the raster to a single dask value by applying std across all bands.
All arguments are ignored.
- sum(*args, **kwargs)#
Reduce the raster to a single dask value by applying sum across all bands.
All arguments are ignored.
- to_null_mask()[source]#
Returns a boolean Raster with True at null values and False otherwise.
- Returns
The resulting mask Raster. It is True where this raster contains null values and False everywhere else.
- Return type
- to_vector()[source]#
Convert the raster into a vector where each non-null cell is a point.
The resulting points are located at the center of each grid cell.
- Returns
The result is a dask_geopandas GeoDataFrame with the following columns: value, row, col, geometry. The value is the cell value at the row and column in the raster.
- Return type
result
- property values#
The raw internal raster as a numpy array.
Note
This triggers computation and loads the raster data into memory.
- var(*args, **kwargs)#
Reduce the raster to a single dask value by applying var across all bands.
All arguments are ignored.
- where(condition, other)[source]#
Filter elements from this raster according to condition.
- Parameters
condition (str or Raster) – A boolean or int raster that indicates where elements in this raster should be preserved and where other should be used. If the condition is an int raster, it is coerced to bool using condition > 0.
Truecells pull values from this raster andFalsecells pull from other. str is treated as a path to a raster.other (scalar, str or Raster) – A raster or value to use in locations where condition is
False. str is treated as a path to a raster.
- Returns
The resulting filtered Raster.
- Return type
- property x#
The x (horizontal) coordinate values.
- property xdata#
The underlying
xarray.DataArray(read only)
- property xmask#
The null value mask as an xarray DataArray.
- property xrs#
- xy(row, col, offset='center')[source]#
Return the (x, y) coordinates of the pixel at (row, col).
- Parameters
row (int, float, array-like) – row value(s) in the raster’s CRS
col (int, float, array-like) – row value(s) in the raster’s CRS
offset (str, optional) –
Determines if the returned coordinates are for the center or a corner. Default is ‘center’
- ’center’
The pixel center.
- ’ul’
The upper left corner.
- ’ur’
The upper right corner.
- ’ll’
The lower left corner.
- ’lr’
The lower right corner.
- Returns
(x value(s), y value(s)). If the inputs where array-like, the output values will be arrays.
- Return type
tuple
- property y#
The y (vertical) coordinate values.
raster_tools.stat_common module#
raster_tools.surface module#
Surface module used to perform common surface analyses on Raster objects.
ref: https://pro.arcgis.com/en/pro-app/latest/tool-reference/spatial-analyst/an-overview-of-the-surface-tools.htm ref: https://github.com/makepath/xarray-spatial
- raster_tools.surface.aspect(raster)[source]#
Calculates the aspect of each raster cell for each raster band.
The approach is based on ESRI’s aspect calculation.
- Parameters
raster (Raster or path str) – The raster to perform the calculation on (typically an elevation surface).
- Returns
The resulting raster of aspect (degrees). The bands will have the same shape as the original Raster.
- Return type
Raster
References
- raster_tools.surface.curvature(raster)[source]#
Calculates the curvature of each raster cell for each raster band.
The approach is based on ESRI’s curvature calculation.
- Parameters
raster (Raster or path str) – The raster to perform the calculation on (typically an elevation surface).
- Returns
The resulting raster of curvature. The bands will have the same shape as the original Raster.
- Return type
Raster
References
- raster_tools.surface.easting(raster, is_aspect=False)[source]#
Calculates the easting component of each raster cell for each band.
- Parameters
raster (Raster or path str) – The raster to perform the calculation on (typically an aspect or elevation surface).
is_aspect (bool) – Indicates if raster is an aspect raster or an elevation raster. The default is false and assumes that an elevation raster is used.
- Returns
The resulting raster of easting (-1 to 1). The bands will have the same shape as the original raster.
- Return type
Raster
- raster_tools.surface.hillshade(raster, azimuth=315, altitude=45)[source]#
Calculates the hillshade component of each raster cell for each band.
This approach is based on ESRI’s hillshade calculation.
- Parameters
raster (Raster or path str) – The raster to perform the calculation on (typically a elevation surface).
azimuth (scalar) – The azimuth of the sun (degrees).
altitude (scalar) – The altitude of the sun (degrees).
- Returns
The resulting raster of hillshade values (0-255, uint8). The bands will have the same shape as the original Raster. The null value is set to 255.
- Return type
Raster
References
- raster_tools.surface.northing(raster, is_aspect=False)[source]#
Calculates the nothing component of each raster cell for each band.
- Parameters
raster (Raster or path str) – The raster to perform the calculation on (typically an aspect or elevation surface).
is_aspect (bool, optional) – Indicates if raster is an aspect raster or an elevation raster. The default is false and assumes that an elevation raster is used.
- Returns
The resulting raster of northing (-1 to 1). The bands will have the same shape as the original Raster.
- Return type
Raster
- raster_tools.surface.slope(raster, degrees=True)[source]#
Calculates the slope (degrees) of each raster cell for each raster band.
The approach is based on ESRI’s degree slope calculation.
- Parameters
raster (Raster or path str) – The raster to perform the calculation on (typically an elevation surface).
degrees (bool) – Indicates whether to output as degrees or percent slope values. Default is True (degrees).
- Returns
The resulting raster of slope values (degrees or percent). The bands will have the same shape as the original Raster.
- Return type
Raster
References
- raster_tools.surface.surface_area_3d(raster)[source]#
Calculates the 3D surface area of each raster cell for each raster band.
The approach is based on Jense, 2004.
- Parameters
raster (Raster or path str) – The raster to perform the calculation on (typically an elevation surface).
- Returns
The resulting raster of 3D surface area. The bands will have the same shape as the original Raster.
- Return type
Raster
References
- raster_tools.surface.tpi(dem, annulus_inner, annulus_outer)[source]#
Compute the Topographic Position Index of a DEM.
This function compares each elevation value to the mean of its neighborhood to produce a scale-dependent index that highlights ridges (positive values) and valleys (negative valleys). Values close to zero, indicate areas with constant slope such as plains (slope of zero). The basic function looks like this:
tpi = int(dem - focalmean(dem, annulus_inner, annulus_outer) + 0.5)An annulus (donut) is used to select the neighborhood of each pixel. Larger radii values select features at larger scales.
- Parameters
dem (Raster or path str) – The DEM raster to use for TPI analysis.
annulus_inner (int) – The inner radius of the annulus. If
0, a circle of radius annulus_outer is used to select the neighborhood.annulus_outer (int) – The outer radius of the annulus. Must be greater than annulus_inner.
- Returns
tpi – The resulting TPI index for dem at the scale determined by the annulus radii.
- Return type
Raster
References
Weiss AD (2001) Topographic position and landforms analysis. Conference poster for ‘21st Annual ESRI International User Conference’, 9–13 July 2001, San Diego, CA. Available at http://www.jennessent.com/arcview/TPI_Weiss_poster.htm
raster_tools.utils module#
raster_tools.vector module#
- class raster_tools.vector.Vector(geo, size=None)[source]#
Bases:
objectA class representing vector data.
Take care to provide the actual number of features in the data when creating a new Vector.
- property bounds#
(minx, miny, maxx, maxy).
If the vector is lazy, the output is a dask array.
- Type
Return a bounds array or dask array
- buffer(*args, **kwargs)[source]#
Apply the buffer operation to the vector geometries.
- Parameters
*args (positional args) – Arguments to be passed on to GoePandas.
**kwargs (keyword args) – Keyword arguments to be passed onto GeoPandas.
- Returns
The buffered vector.
- Return type
- cast_field(name, dtype)[source]#
Cast a field to the specified dtype.
- Parameters
name (str) – The field name to cast.
dtype (str, type, or numpy.dtype) – The dtype to cast to.
- Returns
A new vector with the updated attribute table.
- Return type
- property crs#
The vector CRS.
- property data#
- property field_dtypes#
The field dtypes.
- property field_names#
The field names.
- property field_schema#
A mapping of the field names to dtypes.
- property geometry#
The vector geometry series.
- save(path, **fiona_kwargs)[source]#
Save the vector data to a file.
By default, an ESRI shapefile is written.
- Parameters
path (str) – Output location to save the vector data to.
**fiona_kwargs (keyword args) – Keyword arguments to pass on to
fiona.open()such aslayer='name',driver='GPKG', ormode='a'
- Returns
Returns a new vector pointing to the saved location.
- Return type
- property shape#
The shape of the attribute table.
- simplify(*args, **kwargs)[source]#
Simplify the vector geometries.
- Parameters
*args (positional args) – Arguments to be passed on to GoePandas.
**kwargs (keyword args) – Keyword arguments to be passed onto GeoPandas.
- Returns
The simplify vector.
- Return type
- property size#
The number of vectors contained. NaN is returned if the vector is lazy.
Use len(vector) to trigger computation of the length.
- property table#
The vector attribute table.
- property tasks#
The number of lazy operations left to be computed.
- to_crs(crs)[source]#
Transform the vector coordinates to the specified crs.
- Parameters
crs (str,
pyproj.CRS) – The crs to transform the vector coordinates to. The value can be anything accepted bypyproj.CRS.from_user_input(), such as an EPSG string (eg “EPSG:4326”) or a WKT string.- Return type
The transformed vector(s).
- to_lazy(npartitions=None)[source]#
Converts to a lazy dask-backed Vector.
- Parameters
npartitions (int) – The number of partitions to use.
- Returns
A lazy copy of the vector.
- Return type
- to_raster(like, field=None, all_touched=True)[source]#
Convert vector data to a raster.
- Parameters
like (Raster) – A to use for grid and CRS information. The resulting raster will be on the same grid as like.
field (str, optional) – The name of a field to use for fill values when rasterizing the vector features.
all_touched (bool, optional) – If
True, grid cells that the vector touches will be burned in. If False, only cells with a center point inside of the vector perimeter will be burned in.
- Returns
The resulting raster. The result will have a single band. Each vector shape is assigned a 1-based integer value equal to its order in the original vector collection. This integer value is what is burned in at the corresponding grid cells. The dtype of the result will be the minimum, unsigned integer type that can fit the ID values. The null value is 0.
- Return type
Raster
- to_raster_mask(like, all_touched=True)[source]#
Convert vector data to a raster mask.
- Parameters
like (Raster) – A to use for grid and CRS information. The resulting raster will be on the same grid as like.
all_touched (bool, optional) – If
True, grid cells that the vector touches will be burned in. If False, only cells with a center point inside of the vector perimeter will be burned in.
- Returns
The resulting raster. The result will have a single band. All cells that fall under the vector data are masked with
1. The null value is 0.- Return type
Raster
- raster_tools.vector.count_layer_features(path, layer)[source]#
Count the number of features in a layer of a vector source file.
- Parameters
path (str) – The path to a vector source file.
layer (str, int) – The layer to count features from. Can be the 0-based index or a string.
- Returns
The number of features.
- Return type
int
- raster_tools.vector.open_vectors(path, layers=None)[source]#
Open a vector source.
This can be any GDAL/OGR compatible source.
- Parameters
path (str, Path) – The vector source path.
layers (list of int, int, list of str, str, or None, optional) – The layer(s) to read from the source. This can be a single layer int or string, a list of layer ints/strings, or
None. IfNone, all layers are read in. If int(s) are given, they are treated as 0-based layer indices.
- Returns
If only a single layer was specified or found, a single Vector object is returned. Otherwise, a list of Vector objects is returned.
- Return type
Vector, list of Vector
raster_tools.zonal module#
- raster_tools.zonal.zonal_stats(features, data_raster, stats, raster_feature_values=None)[source]#
Apply stat functions to a raster based on a set of features.
- Parameters
features (str, Vector, Raster) – A Vector or path string pointing to a vector file or a categorical Raster. The vector features are used like cookie cutters to pull data from the data_raster bands. If features is a Raster, it must be an int dtype and have only one band.
data_raster (Raster, str) – A Raster or path string pointing to a raster file. The data raster to pull data from and apply the stat functions to.
stats (str, list of str) –
A single string or list of strings corresponding to stat funcstions. These functions will be applied to the raster data for each of the features in features. Valid string values:
- ’asm’
Angular second moment. Applies -sum(P(g)**2) where P(g) gives the probability of g within the neighborhood.
- ’count’
Count valid cells.
- ’entropy’
Calculates the entropy. Applies -sum(P(g) * log(P(g))). See ‘asm’ above.
- ’max’
Find the maximum value.
- ’mean’
Calculate the mean.
- ’median’
Calculate the median value.
- ’min’
Find the minimum value.
- ’mode’
Compute the statistical mode of the data. In the case of a tie, the lowest value is returned.
- ’std’
Calculate the standard deviation.
- ’sum’
Calculate the sum.
- ’unique’
Count unique values.
- ’var’
Calculate the variance.
raster_feature_values (sequence of ints, optional) – Unique values to be used when the features argument is a Raster. If features is a Raster and this is not provided the unique values in the raster will be calculated.
- Returns
A delayed dask DataFrame. The columns are the values in stats plus a column indicating the band the calculation was carried out on. Each row is the set of statistical calculations carried out on data pulled from data_raster based on the corresponding feature in features. NaN values indicate where a feature was outside of the raster or all data under the feature was null.
- Return type
dask.dataframe.DataFrame
Module contents#
- class raster_tools.Raster(raster, _fast_path=False)[source]#
Bases:
raster_tools.raster._RasterBaseAbstraction of georeferenced raster data with lazy function evaluation.
Raster is a wrapper around xarray Datasets and DataArrays. It takes advantage of xarray’s dask integration to allow lazy loading and evaluation. It allows a pipeline of operations on underlying raster sources to be built in a lazy fashion and then evaluated effiently. Most mathematical operations have been overloaded so operations such as
z = x - yandr = x**2are possible.All operations on a Raster return a new Raster.
- Parameters
raster (str, Raster, xarray.DataArray, xarray.Dataset, numpy.ndarray) – The raster source to use for this Raster. If raster is a string, it is treated like a path. If raster is a Raster, a copy is made and its raster source is used. If raster is an xarray DataArray, Dataset, or numpy array, it is used as the source. Dataset objects must contain ‘raster’ and ‘mask’ variables. The dimensions of these variables are assumed to be “band”, “y”, “x”, in that order. The ‘mask’ variable must have boolean dtype.
- property affine#
The affine transformation for the raster data.
This is an
affine.Affineobject.
- all(*args, **kwargs)#
Reduce the raster to a single dask value by applying all across all bands.
All arguments are ignored.
- any(*args, **kwargs)#
Reduce the raster to a single dask value by applying any across all bands.
All arguments are ignored.
- astype(dtype, warn_about_null_change=True)[source]#
Return a copy of the Raster cast to the specified type.
- Parameters
dtype (str, type, numpy.dtype) – The new type to cast the raster to. The null value will also be cast to this type. If the null value cannot be safely cast to the new type, a default null value for the given dtype is used. This will produce a warning unless warn_about_null_change is set to
False.warn_about_null_change (bool, optional) – Can be used to silence warnings. The default is to always warn about null value changes.
- Returns
The new dtype raster.
- Return type
- property bandwise#
Returns an adapter for band-wise operations on this raster
The returned adapter allows lists/arrays of values to be mapped to the raster’s bands for binary operations.
- property bounds#
Bounds tuple (minx, miny, maxx, maxy)
- burn_mask()[source]#
Fill null-masked cells with null value.
Use this as a way to return the underlying data to a known state. If dtype is boolean, the null cells are set to
Trueinstead of promoting to fit the null value.
- chunk(chunks)[source]#
Rechunk the underlying raster
- Parameters
chunks (tuple of int) – The chunk sizes for each dimension (“band”, “y”, “x”, in that order). Must be a 3-tuple.
- Returns
The rechunked raster
- Return type
- property crs#
The raster’s CRS.
This is a
rasterio.crs.CRSobject.
- property data#
The underlying dask array of data
- property dtype#
The dtype of the data.
- eval()[source]#
Compute any applied operations and return the result as new Raster.
Note that the unerlying sources will be loaded into memory for the computations and the result will be fixed in memory. The original Raster will be unaltered.
- get_bands(bands)[source]#
Retrieve the specified bands as a new Raster. Indexing starts at 1.
- Parameters
bands (int or sequence of ints) – The band or bands to be retrieved. A single band Raster is returned if bands is an int and a multiband Raster is returned if it is a sequence. The band numbers may be out of order and contain repeated elements. if bands is a sequence, the multiband raster’s bands will be in the order provided.
- Returns
The resulting raster composed of the specified bands in the order given.
- Return type
- index(x, y)[source]#
Return the (row, col) index of the pixel at (x, y).
- Parameters
x (float, array-like) – x value(s) in the raster’s CRS
y (float, array-like) – y value(s) in the raster’s CRS
- Returns
(row value(s), col value(s)). If the inputs where array-like, the output values will be arrays.
- Return type
tuple
- property mask#
The null value mask as a dask array.
- max(*args, **kwargs)#
Reduce the raster to a single dask value by applying max across all bands.
All arguments are ignored.
- mean(*args, **kwargs)#
Reduce the raster to a single dask value by applying mean across all bands.
All arguments are ignored.
- min(*args, **kwargs)#
Reduce the raster to a single dask value by applying min across all bands.
All arguments are ignored.
- property nbands#
The number of bands.
- property null_value#
The raster’s null value used to fill missing or invalid entries.
- plot(*args, **kwargs)[source]#
Plot the raster. Args and kwargs are passed to xarray’s plot function.
- prod(*args, **kwargs)#
Reduce the raster to a single dask value by applying prod across all bands.
All arguments are ignored.
- property pxrs#
- reclassify(remapping, unmapped_to_null=False)[source]#
Reclassify raster values based on a mapping.
The raster must have an integer type.
- Parameters
remapping (str, dict) – Can be either a
dictor a path string. If adictis provided, the keys will be reclassified to the corresponding values. If a path string, it is treated as an ASCII remap file where each line looks likea:bandaandbare integers. All remap values (both from and to) must be integers.unmapped_to_null (bool, optional) – If
True, values not included in the mapping are instead mapped to the null value. Default isFalse.
- Returns
The remapped raster.
- Return type
- remap_range(mapping, inclusivity='left')[source]#
Remaps values based on a mapping or list of mappings.
Mappings are applied all at once with earlier mappings taking precedence.
- Parameters
mapping (3-tuple of scalars or list of 3-tuples of scalars) – A tuple or list of tuples containing
(min, max, new_value)scalars. The mappiing(s) map values between the min and max to thenew_value. If mapping is a list and there are mappings that conflict or overlap, earlier mappings take precedence. inclusivity determines which sides of the range are inclusive and exclusive.inclusivity (str, optional) –
Determines whether to be inclusive or exclusive on either end of the range. Default is ‘left’.
- ’left’ [min, max)
Left (min) side is inclusive and right (max) side is exclusive.
- ’right’ (min, max]
Left (min) side is exclusive and right (max) side is inclusive.
- ’both’ [min, max]
Both sides are inclusive.
- ’none’ (min, max)
Both sides are exclusive.
- Returns
The resulting Raster.
- Return type
See also
- replace_null(value)[source]#
Replaces null values with value.
- Parameters
value (scalar) – The new value to replace null values with.
- Returns
The new resulting Raster. If value is a float and the raster dtype is int, the raster type will be promoted to float.
- Return type
- property resolution#
The x and y cell sizes as a tuple. Values are always positive.
- round(decimals=0)[source]#
Evenly round to the given number of decimals
- Parameters
decimals (int, optional) – The number of decimal places to round to. If negative, value specifies the number of positions to the left of the decimal point. Default is 0.
- Returns
Rounded raster.
- Return type
- save(path, no_data_value=None, **gdal_kwargs)[source]#
Compute the final raster and save it to the provided location.
- Parameters
path (str) – The target location to save the raster to.
no_data_value (scalar, optional) – A new null value to use when saving.
**gdal_kwargs (kwargs, optional) – Additional keyword arguments to to pass to rasterio and GDAL when writing the raster data.
- Returns
A raster pointing to the saved location.
- Return type
- set_crs(crs)[source]#
Set the CRS for the underlying data.
- Parameters
crs (object) – The desired CRS. This can be anything accepted by
rasterio.crs.CRS.from_user_input(i.e. 4326, “epsg:4326”, etc).- Returns
A new raster with the specified CRS.
- Return type
- set_null_value(value)[source]#
Sets or replaces the null value for the raster.
If there was previously no null value for the raster, one is set. If there was already a null value, then it is replaced. If the raster has an integer dtype and value is a float, the dtype will be promoted to a float dtype. If value is None, the null value is cleared. The raster data is not changed in this case.
- Parameters
value (scalar or None) – The new null value for the raster. If None, the resulting raster will have no null value, i.e. the null value is cleared.
- Returns
The new resulting Raster.
- Return type
- property shape#
The shape of the underlying raster. Dim 0 is the band dimension.
The shape will always be of the form
(B, Y, X)whereBis the band dimension,Yis the y dimension, andXis the x dimension.
- std(*args, **kwargs)#
Reduce the raster to a single dask value by applying std across all bands.
All arguments are ignored.
- sum(*args, **kwargs)#
Reduce the raster to a single dask value by applying sum across all bands.
All arguments are ignored.
- to_null_mask()[source]#
Returns a boolean Raster with True at null values and False otherwise.
- Returns
The resulting mask Raster. It is True where this raster contains null values and False everywhere else.
- Return type
- to_vector()[source]#
Convert the raster into a vector where each non-null cell is a point.
The resulting points are located at the center of each grid cell.
- Returns
The result is a dask_geopandas GeoDataFrame with the following columns: value, row, col, geometry. The value is the cell value at the row and column in the raster.
- Return type
result
- property values#
The raw internal raster as a numpy array.
Note
This triggers computation and loads the raster data into memory.
- var(*args, **kwargs)#
Reduce the raster to a single dask value by applying var across all bands.
All arguments are ignored.
- where(condition, other)[source]#
Filter elements from this raster according to condition.
- Parameters
condition (str or Raster) – A boolean or int raster that indicates where elements in this raster should be preserved and where other should be used. If the condition is an int raster, it is coerced to bool using condition > 0.
Truecells pull values from this raster andFalsecells pull from other. str is treated as a path to a raster.other (scalar, str or Raster) – A raster or value to use in locations where condition is
False. str is treated as a path to a raster.
- Returns
The resulting filtered Raster.
- Return type
- property x#
The x (horizontal) coordinate values.
- property xdata#
The underlying
xarray.DataArray(read only)
- property xmask#
The null value mask as an xarray DataArray.
- property xrs#
- xy(row, col, offset='center')[source]#
Return the (x, y) coordinates of the pixel at (row, col).
- Parameters
row (int, float, array-like) – row value(s) in the raster’s CRS
col (int, float, array-like) – row value(s) in the raster’s CRS
offset (str, optional) –
Determines if the returned coordinates are for the center or a corner. Default is ‘center’
- ’center’
The pixel center.
- ’ul’
The upper left corner.
- ’ur’
The upper right corner.
- ’ll’
The lower left corner.
- ’lr’
The lower right corner.
- Returns
(x value(s), y value(s)). If the inputs where array-like, the output values will be arrays.
- Return type
tuple
- property y#
The y (vertical) coordinate values.
- class raster_tools.Vector(geo, size=None)[source]#
Bases:
objectA class representing vector data.
Take care to provide the actual number of features in the data when creating a new Vector.
- property bounds#
(minx, miny, maxx, maxy).
If the vector is lazy, the output is a dask array.
- Type
Return a bounds array or dask array
- buffer(*args, **kwargs)[source]#
Apply the buffer operation to the vector geometries.
- Parameters
*args (positional args) – Arguments to be passed on to GoePandas.
**kwargs (keyword args) – Keyword arguments to be passed onto GeoPandas.
- Returns
The buffered vector.
- Return type
- cast_field(name, dtype)[source]#
Cast a field to the specified dtype.
- Parameters
name (str) – The field name to cast.
dtype (str, type, or numpy.dtype) – The dtype to cast to.
- Returns
A new vector with the updated attribute table.
- Return type
- property crs#
The vector CRS.
- property data#
- property field_dtypes#
The field dtypes.
- property field_names#
The field names.
- property field_schema#
A mapping of the field names to dtypes.
- property geometry#
The vector geometry series.
- save(path, **fiona_kwargs)[source]#
Save the vector data to a file.
By default, an ESRI shapefile is written.
- Parameters
path (str) – Output location to save the vector data to.
**fiona_kwargs (keyword args) – Keyword arguments to pass on to
fiona.open()such aslayer='name',driver='GPKG', ormode='a'
- Returns
Returns a new vector pointing to the saved location.
- Return type
- property shape#
The shape of the attribute table.
- simplify(*args, **kwargs)[source]#
Simplify the vector geometries.
- Parameters
*args (positional args) – Arguments to be passed on to GoePandas.
**kwargs (keyword args) – Keyword arguments to be passed onto GeoPandas.
- Returns
The simplify vector.
- Return type
- property size#
The number of vectors contained. NaN is returned if the vector is lazy.
Use len(vector) to trigger computation of the length.
- property table#
The vector attribute table.
- property tasks#
The number of lazy operations left to be computed.
- to_crs(crs)[source]#
Transform the vector coordinates to the specified crs.
- Parameters
crs (str,
pyproj.CRS) – The crs to transform the vector coordinates to. The value can be anything accepted bypyproj.CRS.from_user_input(), such as an EPSG string (eg “EPSG:4326”) or a WKT string.- Return type
The transformed vector(s).
- to_lazy(npartitions=None)[source]#
Converts to a lazy dask-backed Vector.
- Parameters
npartitions (int) – The number of partitions to use.
- Returns
A lazy copy of the vector.
- Return type
- to_raster(like, field=None, all_touched=True)[source]#
Convert vector data to a raster.
- Parameters
like (Raster) – A to use for grid and CRS information. The resulting raster will be on the same grid as like.
field (str, optional) – The name of a field to use for fill values when rasterizing the vector features.
all_touched (bool, optional) – If
True, grid cells that the vector touches will be burned in. If False, only cells with a center point inside of the vector perimeter will be burned in.
- Returns
The resulting raster. The result will have a single band. Each vector shape is assigned a 1-based integer value equal to its order in the original vector collection. This integer value is what is burned in at the corresponding grid cells. The dtype of the result will be the minimum, unsigned integer type that can fit the ID values. The null value is 0.
- Return type
- to_raster_mask(like, all_touched=True)[source]#
Convert vector data to a raster mask.
- Parameters
like (Raster) – A to use for grid and CRS information. The resulting raster will be on the same grid as like.
all_touched (bool, optional) – If
True, grid cells that the vector touches will be burned in. If False, only cells with a center point inside of the vector perimeter will be burned in.
- Returns
The resulting raster. The result will have a single band. All cells that fall under the vector data are masked with
1. The null value is 0.- Return type
- raster_tools.band_concat(rasters)[source]#
Join a sequence of rasters along the band dimension.
- Parameters
rasters (sequence of Rasters and/or paths) – The rasters to concatenate. These can be a mix of Rasters and paths. All rasters must have the same shape in the x and y dimensions.
- Returns
The resulting concatenated Raster.
- Return type
- raster_tools.constant_raster(raster_template, value=1, bands=1)[source]#
Create a Raster filled with a contant value like a template raster.
This is a convenience function that wraps
full_like().- Parameters
raster_template (Raster, str) – Template raster used to define rows, columns, crs, resolution, etc
value (scalar, optional) – Value to fill result with. Default is 1.
bands (int, optional) – Number of bands desired for output. Default is 1.
- Returns
The resulting raster of constant values.
- Return type
- raster_tools.count_layer_features(path, layer)[source]#
Count the number of features in a layer of a vector source file.
- Parameters
path (str) – The path to a vector source file.
layer (str, int) – The layer to count features from. Can be the 0-based index or a string.
- Returns
The number of features.
- Return type
int
- raster_tools.empty_like(raster_template, bands=1, dtype=None)[source]#
Create a Raster filled with uninitialized data like a template raster.
- Parameters
raster_template (Raster, str) – Template raster used to define rows, columns, crs, resolution, etc
bands (int, optional) – Number of bands desired for output. Default is 1.
dtype (data-type, optional) – Overrides the result dtype.
- Returns
The resulting raster of uninitialized data.
- Return type
- raster_tools.full_like(raster_template, value, bands=1, dtype=None)[source]#
Create a Raster filled with a contant value like a template raster.
- Parameters
raster_template (Raster, str) – Template raster used to define rows, columns, crs, resolution, etc
value (scalar) – Value to fill result with.
bands (int, optional) – Number of bands desired for output. Default is 1.
dtype (data-type, optional) – Overrides the result dtype.
- Returns
The resulting raster of constant values.
- Return type
- raster_tools.ones_like(raster_template, bands=1, dtype=None)[source]#
Create a Raster filled with ones like a template raster.
- raster_tools.open_vectors(path, layers=None)[source]#
Open a vector source.
This can be any GDAL/OGR compatible source.
- Parameters
path (str, Path) – The vector source path.
layers (list of int, int, list of str, str, or None, optional) – The layer(s) to read from the source. This can be a single layer int or string, a list of layer ints/strings, or
None. IfNone, all layers are read in. If int(s) are given, they are treated as 0-based layer indices.
- Returns
If only a single layer was specified or found, a single Vector object is returned. Otherwise, a list of Vector objects is returned.
- Return type
Vector, list of Vector
- raster_tools.random_raster(raster_template, distribution='normal', bands=1, params=(1, 0.5))[source]#
Creates a Raster of random values based on the desired distribution.
This function uses dask.array.random to generate data. The default is a normal distribution with mean of 1 and standard deviation of 0.5.
- Parameters
raster_template (Raster, str) – A template raster used to define rows, columns, crs, resolution, etc.
distribution (str, optional) –
Random distribution type. Default is ‘normal’. See params parameter below for passing additional distribution parameters. Valid values are:
- ’binomial’
Binomial distribution. Uses two additional parameters: (n, p).
- ’normal’
Normal distribution. Uses two additional parameters: (mean, std). This is the default.
- ’poisson’
Poisson distribution. Uses one additional parameter.
- ’uniform’
Uniform distribution in the half-open interval [0, 1). Uses no additional.
- ’weibull’
Weibull distribution. Uses one additional parameter.
bands (int, optional) – Number of bands needed desired. Default is 1.
params (list of scalars, optional) – Additional parameters for generating the distribution. For example distribution=’normal’ and params=(1, 0.5) would result in a normal distribution with mean of 1 and standard deviation of 0.5. Default is
(1, 0.5).
- Returns
The resulting raster of random values pulled from the distribution.
- Return type
- raster_tools.reclassify(raster, remapping, unmapped_to_null=False)[source]#
Reclassify the input raster values based on a mapping.
This function only works with integer type rasters.
- Parameters
raster (str, Raster) – The input raster to reclassify. Can be a path string or Raster object. The raster dtype must be integer.
remapping (str, dict) – Can be either a
dictor a path string. If adictis provided, the keys will be reclassified to the corresponding values. If a path string, it is treated as an ASCII remap file where each line looks likea:bandaandbare integers. All remap values (both from and to) must be integers.unmapped_to_null (bool, optional) – If
True, values not included in the mapping are instead mapped to the null value. Default isFalse.
- Returns
The remapped raster.
- Return type
- raster_tools.remap_range(raster, mapping, inclusivity='left')[source]#
Remaps values based on a mapping or list of mappings.
Mappings are applied all at once with earlier mappings taking precedence.
- Parameters
raster (Raster or str) – Path string or Raster to perform remap on.
mapping (3-tuple of scalars or list of 3-tuples of scalars) – A tuple or list of tuples containing
(min, max, new_value)scalars. The mappiing(s) map values between the min and max to thenew_value. If mapping is a list and there are mappings that conflict or overlap, earlier mappings take precedence. inclusivity determines which sides of the range are inclusive and exclusive.inclusivity (str, optional) –
Determines whether to be inclusive or exclusive on either end of the range. Default is ‘left’.
- ’left’ [min, max)
Left (min) side is inclusive and right (max) side is exclusive.
- ’right’ (min, max]
Left (min) side is exclusive and right (max) side is inclusive.
- ’both’ [min, max]
Both sides are inclusive.
- ’none’ (min, max)
Both sides are exclusive.
- Returns
The resulting Raster.
- Return type