pywatemsedem.geo package
Submodules
pywatemsedem.geo.factory module
- class pywatemsedem.geo.factory.Factory(resolution, epsg_code, nodata, resmap, bounds=None)[source]
Bases:
objectFactory class for generating vectors and rasters.
Used to enable functions to generate vectors and rasters with consistent spatial properties (resolution, EPSG code, nodata value).
- mask
Mask raster or vector polygon file.
- Type:
pathlib.Path or str
- rp
Raster properties instance.
Notes
By default a rasterproperties instance is made in the initialisation. See
pywatemsedem.geo.factory.create_mask()-function. This can be toggled off by settingpywatemsedem.geo.factory.Factory.create_rasterpropertiesto False.- create_mask(mask)[source]
Create mask based on a mask template (raster or vector)
- Parameters:
mask (pathlib.Path | str) – File path to mask vector or raster file
Notes
If
pywatemsedem.geo.factory.Factory.create_rasterpropertiesis set to False, one needs to self-define a RasterProperties instance.
- property mask
AbstractRaster mask
- raster_factory(raster_input, flag_clip=True, flag_mask=True, allow_nodata_array=False)[source]
Raster factory to load rasters in memory
- Parameters:
raster_input (str, pathlib.Path or numpy.ndarray) – Input raster file or numpy array
flag_clip (bool, default True) – Clip raster (True)
flag_mask (bool, default True) – Mask raster (True)
allow_nodata_array (default False) – Allow the returned array to only contain nodata-values, see
pywatemsedem.geo.rasters.AbstractRaster.mask().
- Returns:
raster – See
pywatemsedem.geo.rasters.AbstractRaster- Return type:
- property rp
RasterProperties. See
pywatemsedem.geo.rasterproperties.RasterProperties
- property vct_mask
AbstractVector mask, See
pywatemsedem.geo.vectors.AbstractVector
- vector_factory(vector_input, geometry_type, allow_empty=False, flag_clip=True)[source]
Vector factory to load vectors in memory
- Parameters:
vector_input (str, pathlib.Path or geopandas.GeoDataFrame) – Input vector file or geopandas dataframe
mask (bool, default True) – Mask vector (True), nodata value will be that one of pywatemsedem.geo.factory.Factory.rp.
allow_empty (bool, default False) – Allow vector to be empty, see
pywatemsedem.geo.vectors.AbstractVectorflag_clip (bool, default True) – Clip vector to mask
- Returns:
vector – See
pywatemsedem.geo.vectors.AbstractVector- Return type:
pywatemsedem.geo.rasters.AbstractVector
- pywatemsedem.geo.factory.valid_mask_factory(func)[source]
Decorator to check if a valid mask is set before using raster or vector factory.
- Parameters:
func (callable) – The function to wrap.
- Returns:
Wrapped function that validates mask existence.
- Return type:
callable
- Raises:
PywatemsedemInputError – If the mask has not been created.
pywatemsedem.geo.rasterproperties module
- class pywatemsedem.geo.rasterproperties.RasterProperties(bounds: List[float], resolution: int, nodata: float, epsg: int, driver: str = 'GTiff')[source]
Bases:
objectRaster properties class.
Pywatemsedem makes use of rasterio and gdal for loading, writing and processing rasters/vectors. A small class is implemented to easily switch between raster geographic references of gdal and rasterio, respectively names gdal_profile and rasterio_profile. Assuming you start with loading a raster with rasterio:
from pywatemsedem.geo.utils import load_raster from pywatemsedem.geo.rasterproperties import RasterProperties arr, _, rasterio_profile = load_raster("test.tif") rp = RasterProperties.from_rasterio(rasterio_profile) rp.gdal_profile ...
Note that
rasterio_profileis of type dictionary, as such one can start from a profile definition in a dictionary format, for instance for gdal:from pywatemsedem.geo.utils import load_raster from pywatemsedem.geo.rasterproperties import RasterProperties gdal_profile = { "nodata": -9999.0, "epsg": "EPSG:31370", "res": 20.0, "minmax": [201620.0, 153880.0, 207500.0, 164060.0], "ncols": 294, "nrows": 509, } rp = RasterProperties.from_gdal(gdal_profile) rp.rasterio_profile ...
In addition, a
RasterProfileinstance can be generated from known raster bounds and a raster resolution (this can be useful for generating raster geographical references when no rasterio or gdal profile definition is available):from pywatemsedem.geo.rasterproperties import RasterProperties bounds = [201620.0, 153880.0, 207500.0, 164060.0] resolution = 20 nodata= -9999 epsg = 31370 rp = RasterProperties(bounds, resolution, nodata, epsg)
- xcoord
1D-vector array of x-coordinates.
- Type:
- ycoord
1D-vector array of y-coordinates.
- Type:
Notes
Current implementation supports storing of raster properties, yet it does not aim to provide functionalities to adapt raster properties (as these functionalities are present in rasterio).
Current implementation does not support tiled rasters. In addition, it only supports bands-interleaving as only single-band rasters are used.
Definition interleaving: the way multiple bands of a raster are saved to the raster (e.g. pixel-based, line-based, band-based).
The coordinate reference system (crs) is defined in EPSG.
Note that dtype in gdal operation is typically derived from input raster dtype that is used to execute the gdal operation. As such dtype is not defined as a key in the gdal_profile property.
- property bounds: List[float]
Raster boundary coordinates.
- Returns:
list – The first entry is x_left, the second entry is y_lower, the third entry is x_right and the fourth entry is y_upper.
- Return type:
[x_left, y_lower, x_right, y_upper]
- property driver: str
Name of GDAL driver
see https://gdal.org/drivers/raster/index.html; only GTiff | RST | SAGA are supported.
- property epsg: int
EPSG code of the raster projection should be a numeric value, see https://epsg.io/
- Type:
- classmethod from_gdal(gdal_profile: dict)[source]
Set RasterProperties from a gdal profile
- Parameters:
gdal_profile (dict)
- classmethod from_rasterio(rasterio_profile: dict, epsg: int = None)[source]
Set RasterProperties with a rasterio profile
- Parameters:
rasterio_profile (dict)
epsg (int, default None) – EPSG code should be a numeric value, see https://epsg.io/.
- property gdal_profile: dict
Return gdal profile
- Returns:
gdal_profile – See definition in this function.
- Return type:
- property rasterio_profile: dict
Return rasterio profile
- Returns:
rasterio_profile – See definition in this function.
- Return type:
- property xcoord
Returns 1D-vector array of x-coordinates
- Return type:
- property ycoord
Returns 1D-vector array of y-coordinates
- Return type:
pywatemsedem.geo.rasters module
- class pywatemsedem.geo.rasters.AbstractRaster[source]
Bases:
objectAbstract raster class based on numpy arrays and raster properties.
- arr
Raster array.
- Type:
- rp
Raster properties instance.
Notes
If an array mask is provided to the initialize method, the array is automatically masked.
- property arr
Return array.
- Returns:
Raster array.
- Return type:
- clip()[source]
Clip function (not implemented).
- Raises:
NotImplementedError – This method is not implemented in the abstract class.
- histogram(fig=None, ax=None, nodata=None, ylogscale=False, *args, **kwargs)[source]
Plot density histogram of raster data values.
Plots histogram with 25th, 50th and 75th percentiles.
- Parameters:
fig (matplotlib.figure.Figure, default None) – If not given, defaults to generating new figure.
ax (matplotlib.axes.Axes, default None) – If not given, defaults to generating new axis.
nodata (float, default None) – Used to mask no data values.
ylogscale (bool, default False) – Log transformation on density axis if True.
*args – Additional positional arguments passed to hist.
**kwargs – Additional keyword arguments passed to hist.
- Returns:
fig (matplotlib.figure.Figure) – Figure object.
ax (matplotlib.axes.Axes) – Axes object.
- initialize(arr, rp, arr_mask=None, allow_nodata_array=False)[source]
Initialize array and raster properties.
- Parameters:
arr (numpy.ndarray) – Raster array.
rp (pywatemsedem.geo.rasterproperties.RasterProperties) – Raster properties instance.
arr_mask (numpy.ndarray, default None) – See
pywatemsedem.geo.rasters.AbstractRaster.mask().allow_nodata_array (bool, default False) – See
pywatemsedem.geo.rasters.AbstractRaster.mask().
- is_empty()[source]
Check if array (raster) is None (empty).
- Returns:
True if array is None, False otherwise.
- Return type:
- mask(arr_mask, allow_nodata_array=False)[source]
Mask the raster array.
- Parameters:
arr_mask (numpy.ndarray) – Array mask (1, nodata). Note that array mask should have same nodata value as raster array.
allow_nodata_array (bool, default False) – Allow to return a nodata-array.
- plot(fig=None, ax=None, nodata=None, *args, **kwargs)[source]
Plot raster array with imshow.
- Parameters:
fig (matplotlib.figure.Figure, default None) – If not given, defaults to generating new figure.
ax (matplotlib.axes.Axes, default None) – If not given, defaults to generating new axis.
nodata (float, default None) – Used to mask certain values present in arr which represent nodata (e.g. -9999).
*args – Additional positional arguments passed to imshow.
**kwargs – Additional keyword arguments passed to imshow.
- Returns:
fig (matplotlib.figure.Figure) – Figure object.
ax (matplotlib.axes.Axes) – Axes object.
- property rp
Return raster properties.
- Returns:
Raster properties instance.
- Return type:
- update_nodata_value(to)[source]
Update the nodata value.
- Parameters:
to (float) – New nodata value.
- write(outfile_path, format='idrisi', dtype=None, nodata=None)[source]
Write raster data to disk.
- Parameters:
outfile_path (pathlib.Path or str) – File path output.
format (str, default "idrisi") – Output format, either “idrisi” or “tiff”.
dtype (numpy.dtype, default None) – Output raster type. If None, dtype of array is used.
nodata (float, default None) – Nodata value for output raster. If None, nodata of rasterproperties is used.
- Returns:
True if write was successful.
- Return type:
- Raises:
NotImplementedError – If format is not supported.
TypeError – If file extension does not match format.
- class pywatemsedem.geo.rasters.RasterFile(file_path, rp=None, arr_mask=None, allow_nodata_array=False)[source]
Bases:
AbstractRasterRaster loaded from an input raster file.
- arr
Raster array.
- Type:
- rp
Raster properties instance.
Notes
If rasterproperties are provided by the user, clipping is automatically done. Inherits from
pywatemsedem.geo.rasters.AbstractRaster.- static clip(file_path, rp, resample='mode')[source]
Clip raster to specified extent.
- Parameters:
file_path (pathlib.Path) – File path to user input raster.
rp (pywatemsedem.geo.rasterproperties.RasterProperties) – Raster properties instance defining the clip extent.
resample (str, default "mode") – Resampling method, either “near” or “mode”. See
pywatemsedem.geo.utils.clip_rst().
- Returns:
Clipped array.
- Return type:
- Raises:
IOError – If clipped output raster is empty.
Notes
Clipping also provides resampling to another resolution. See
pywatemsedem.geo.utils.clip_rst().
- class pywatemsedem.geo.rasters.RasterMemory(arr, rp, arr_mask=None, allow_nodata_array=False)[source]
Bases:
AbstractRasterRaster stored in memory from a numpy array.
- arr
Raster array.
- Type:
- rp
Raster properties instance.
Notes
Inherits from
pywatemsedem.geo.rasters.AbstractRaster.- clip()[source]
Clip function (not implemented for RasterMemory).
- Raises:
NotImplementedError – Clipping is not implemented for RasterMemory class.
- class pywatemsedem.geo.rasters.TemporalRaster(arr, rp, arr_mask=None)[source]
Bases:
object3-D raster with spatial x and y dimensions and a temporal dimension.
The first two dimensions are spatial (x, y), and the third dimension is temporal.
- arr
3D raster array.
- Type:
- rp
Raster properties instance.
Notes
This class only works with array inputs.
- property arr
Return array.
- Returns:
3D raster array.
- Return type:
- plot(nodata=None, *args, **kwargs)[source]
Plot raster sequentially in columns.
- Parameters:
nodata (float, default None) – Used to mask no data values.
*args – Additional positional arguments passed to plot.
**kwargs – Additional keyword arguments passed to plot.
- write(outfiles, format='idrisi', dtype=None)[source]
Write temporal raster data to disk.
- Parameters:
outfiles (list or tuple of pathlib.Path or str) – List of output files, one for each temporal slice.
format (str, default "idrisi") – Output format. See
pywatemsedem.geo.rasters.AbstractRaster.write().dtype (numpy.dtype, default None) – Output raster type. See
pywatemsedem.geo.rasters.AbstractRaster.write().
- Returns:
True if write was successful.
- Return type:
- Raises:
ValueError – If number of output files does not match temporal dimension.
pywatemsedem.geo.utils module
utils.py
This module provides utility functions for geospatial data processing, including raster and vector data manipulation, rasterization, polygonization, and statistical analysis of raster data within polygon features.
The functions rely on libraries such as rasterio, geopandas, pyogrio, and subprocess to perform various geospatial operations. The module also includes decorators for input validation and type checking to ensure that the functions are used correctly.
- pywatemsedem.geo.utils.any_equal_element_in_vector(geoseries_left, geoseries_right)[source]
Check if there are equal vectors in the left and right geoseries
- Parameters:
geoseries_left (geopandas.GeoSeries)
geoseries_right (geopandas.GeoSeries)
- Returns:
Line strings present in left and right geoseries
- Return type:
- pywatemsedem.geo.utils.check_cuboid_condition(arr_polygon_perimeter, arr_polygon_area)[source]
Check if a shape can be classified as a cuboid
- Parameters:
arr_polygon_perimeter (numpy.ndarray or pandas.Series) – 1D array holding in each row the perimeter of each polygon
arr_polygon_area (numpy.ndarray or pandas.Series) – 1D array holding in each row the area of each polygon
- Returns:
condition – 1D array holding True/False if cuboid
- Return type:
See also
- pywatemsedem.geo.utils.check_raster_properties_raster_with_template(path_check, path_template, epsg)[source]
Check if extent and resolution of new raster and template raster align.
- Parameters:
path_check (pathlib.Path or RasterProperties) – Incoming, new raster.
path_template (pathlib.Path) – Template raster.
epsg (int) – EPSG code of the cartographic projection.
- Raises:
ValueError – If extent or resolution does not match.
- pywatemsedem.geo.utils.check_spatial_resolution_rst(rst_in, resolution, precision=0.01)[source]
Check if the resolution of a tiff raster is equal to a defined one
- Parameters:
rst_in (str or pathlib.Path) – File path of input raster
resolution (int) – Resolution to compare with
precision (float, default 0.01) – Precision to check resolution
- Returns:
cond – Equal/non-equal (True/False)
- Return type:
- pywatemsedem.geo.utils.clean_up_tempfiles(temporary_file, file_format)[source]
Clean up extra generated tempfiles
This function can be used to clean-up extra files (for example auxilary files) generated during a write of raster or vector file.
- Parameters:
temporary_file (pathlib.Path | str)
file_format ({"tiff","shp","rst","txt"}) – format of the temporary files
- pywatemsedem.geo.utils.clip_rst(rst_in, rst_out, cnst, resampling='near')[source]
Clip a raster to a certain bounding box with a given resolution.
- Parameters:
rst_in (pathlib.Path or str) – File path to the input raster.
rst_out (pathlib.Path or str) – File path to the destination raster.
cnst (dict) –
Dictionary with following keys:
epsg (str): the EPSG-code of the rst_in.
res (int): resolution.
nodata (int): nodata flag.
minmax (list): list with xmin, ymin, xmax, ymax.
resampling (str, default "near") – Either “mode” or “near”.
Notes
This function uses the gdalwarp CLI, see https://gdal.org/en/stable/programs/gdalwarp.html for more information.
“mode” and “near” have been tested, see https://gdal.org/programs/gdalwarp.html#cmdoption-gdalwarp-r.
- pywatemsedem.geo.utils.compute_statistics_rasters_per_polygon_vector(lst_rasters, vct_polygon, vct_out, lst_names, dict_operators, normalize=True, ton=False)[source]
Compute statistics of a raster per polygon feature.
- Parameters:
lst_rasters (list) – File path rasters (pathlib.Path).
vct_polygon (str) – File path to input polygon vector.
vct_out (str) – File path to output polygon vector.
lst_names (list) – List of output names in output vector for files in lst_rasters.
dict_operators (dict) – Operators. For a description of the dictionary of statistics, see inputs in
pywatemsedem.geo.utils.grid_statistics(). See example for use.normalize (bool, default True) – Normalize with shape area.
ton (bool, default False) – Use ton.
- Returns:
GeoDataFrame with computed statistics.
- Return type:
Notes
The desired statistics are inputted after the file reference of the raster, and are formatted as a dictionary, e.g.:
dict_operators = {"COUNT": True, "SUM": True}
Examples
>>> from pywatemsedem.geo.utils import compute_statistics_rasters_per_polygon_vector >>> vct_aho = "AHO.shp" >>> vct_out = "statistics_aho.shp" >>> rst_sewerin = "sewerin.rst" >>> rst_sediexport = "SediExport.rst" >>> compute_statistics_rasters_per_polygon_vector( ... [rst_sewerin, rst_sediexport], ... vct_polygon, ... vct_out, ... ["River", "Sewers"], ... {"COUNT": True, "SUM": True}, ... ton=True, ... )
- pywatemsedem.geo.utils.create_filename(suffix, directory=PosixPath('tempfiles_pywatemsedem'))[source]
Create temporary filename in a dedicated directory
Create directory if it does not exist
Only filenames are generated, not the files
- Parameters:
suffix (str)
directory (pathlib.Path, default 'tempfiles_pywatemsedem')
- Return type:
- pywatemsedem.geo.utils.create_spatial_index(vct_in)[source]
Creates a qix-file for a given shapefile
- Parameters:
vct_in (str or pathlib.Path) – File path of the input shapefile
Note
Uses and relies on ogrinfo CLI
- pywatemsedem.geo.utils.define_extent_from_vct(vct_catchment, resolution, nodata, epsg, bounds=None, buffer=100)[source]
Read the extent of the catchment
- Parameters:
vct_catchment (str or pathlib.Path) – File path of the vector shapefile
bounds (list, default None) – if None, bounds are determined from The first entry is x_left, the second entry is y_lower, the third entry is x_right and the fourth entry is y_upper [x_left, y_lower, x_right, y_upper].
resolution (int) – Spatial resolution
epsg (int) – EPSG code should be a numeric value, see https://epsg.io/.
- Returns:
rp
- Return type:
RasterProperties see
pywatemsedem.geo.rasterproperties.RasterProperties
- pywatemsedem.geo.utils.delete_rst(rst_in)[source]
Delete a raster dataset.
- Parameters:
rst_in (str or pathlib.Path) – File path of the raster dataset to be deleted.
- pywatemsedem.geo.utils.estimate_width_of_polygon(arr_polygon_perimeter, arr_polygon_area, nan_value=nan)[source]
Estimate the width of a polygon with the length and area of the polygon see also https://gis.stackexchange.com/questions/20279/calculating-average-width-of-polygon/
- Parameters:
arr_polygon_perimeter (numpy.ndarray or pandas.Series) – 1D array holding in each row the perimeter of each polygon
arr_polygon_area (numpy.ndarray or pandas.Series) – 1D array holding in each row the area of each polygon
nan_value (float) – The value to fill in for nan_values
- Returns:
arr_est_polygon_width – 1D array holding in each row the estimated width
- Return type:
Note
The width is only estimated for polygons which approximate a cuboid
The width is estimated by
\[B_gr = 1/4 [A-√(B-C)] 1/4 [P_{poly}-√(〖P_{poly}〗^2-16A_{poly} )]\]with
\(P_{poly}\) = perimeter of polygon
\(A_{poly}\) = area of polygon
See also
- pywatemsedem.geo.utils.execute_saga(cmd_args)[source]
Run saga executable and catch non-informative error.
This function catches saga error command and ignores ‘corrupted size vs. prev_size in fastbins’ error in case output runs from saga are okay.
- pywatemsedem.geo.utils.execute_subprocess(cmd_args)[source]
Run a command line tool
Logs error with command output and error
- Parameters:
cmd_args (list) – list with all argmunts that must be given to the console
- Return type:
Returns True if function call is successfull.
- pywatemsedem.geo.utils.generate_vct_mask_from_raster_mask(rst_catchment, vct_catchment, resolution)[source]
Generate a catchment fileshape from a raster file
- Parameters:
rst_catchment (str or pathlib.Path) – Input raster format of the catchment (can be any type that can be read by rasterio)
vct_catchment (str or pathlib.Path) – output shapefile format of the catchment
resolution (int) – resolution of the model run
- pywatemsedem.geo.utils.get_extent_vct(vct)[source]
Get the bounding box coordinates of a shapefile.
- Parameters:
vct (str or pathlib.Path) – File path of the input shapefile.
- Returns:
xmin, ymin, xmax, ymax.
- Return type:
- pywatemsedem.geo.utils.get_geometry_type(vct)[source]
Get the geometry type of a shapefile.
- Parameters:
vct (str or pathlib.Path) – File path to shapefile.
- Returns:
Geometry type (see GDAL documentation for all possibilities).
- Return type:
- pywatemsedem.geo.utils.get_mask_template(modelinputfolder, catchmentname, rst_template=None)[source]
Get a binary raster from template raster (P-factor)
- Parameters:
modelinputfolder (str or pathlib.Path) – File path to the modelinputfolder of WaTEM/SEDEM
catchmentname (str) – Catchment name
rst_template (str or pathlib.Path, default None) – Path to a template file that can be used as template for geodata and bin mask
- Returns:
arr_bindomain – In domain is equal to one, outside domain is equal to zero.
- Return type:
- pywatemsedem.geo.utils.get_rstparams(ini, epsg=None, template=None)[source]
Get rstparams and rasterprofile from template raster (default:pkaart)
- Parameters:
ini (pathlib.Path) – file path to ini-file of WaTEM-SEDEM
epsg (str, default None) – the epsg code defining the coordinate system of the raster, format = “EPSG:XXXXX”
template (str or pathlib.Path, default None) – File path to a template file that can be used as template for geodata and bin mask. Default the “P” raster is used.
- Returns:
profile (rasterio.profiles) – See
rasterio.profiles.Profilerstparams (dict) – gdal dictionary holding all metadata for idrisi rasters
arr_bindomain (numpy.ndarray) – binary mask of modelling domain
- pywatemsedem.geo.utils.grid_difference(rst_in1, rst_in2, rst_out)[source]
Make the difference between two grids.
- Parameters:
Notes
Uses the SAGA CLI command “grid_calculus” with the option “3” (difference).
- pywatemsedem.geo.utils.grid_statistics(lst_rst, vct_in, vct_out, naming=0, COUNT=False, MIN=False, MAX=False, RANGES=False, SUM=True, MEAN=False)[source]
Calculate zonal statistics for a raster based on polygons
- Parameters:
lst_rst (list) – File paths (str or pathlib.Path) of the input rasters
vct_in (str or pathlib.Path) – File path of the input polygon shapefile
vct_out (str or pathlib.Path) – File path of the output shapefile with the raster statistics
naming (int, default 0) – 1: grid name (note: esrsi shapes ar capped on 10 characters) 0: grid id
COUNT (bool, default False) – Count the raster cells within every polygon
MIN (bool, default False) – Calculate the minimum value within every polygon
MAX (bool, default False) – Calculate the maximum value within every polygon
RANGES (bool, default False) – Calculate the range within every polygon
SUM (bool, default False) – Calculate the sum of all pixel values within every polygon
MEAN (bool, default False) – Calculate the mean of all pixel values within every polygon
Note
Uses and relies on saga_cmd CLI
- pywatemsedem.geo.utils.lines_to_direction(vct_line, rst_out, rst_template)[source]
Convert line features to a direction raster.
This function converts the direction of line features to a raster. See the docs of WaTEM/SEDEM for more information about this raster.
- Parameters:
vct_line (str or pathlib.Path) – File path to the input line shapefile.
rst_out (pathlib.Path) – File path to the output raster.
rst_template (str or pathlib.Path) – File path to a template raster.
Notes
Uses and relies on saga_cmd CLI.
- pywatemsedem.geo.utils.lines_to_raster(vct_line, rst_out, rst_template, field, dtype)[source]
Converts a line shapefile to a raster
- Parameters:
vct_line (str or pathlib.Path) – File path of input line shapefile
rst_out (str or pathlib.Path) – File path of output rasterfile
rst_template (str or pathlib.Path) – File path to a template raster
field (str) – The field of the shapefile containing the values for the raster
dtype (str, default None) – Data type of the values, e.g. Byte/Int16/UInt16/UInt32/Int32/Float32…
Note
Uses and relies on saga_cmd CLI
- pywatemsedem.geo.utils.load_raster(rst, return_bounds=False)[source]
read raster with rasterio as a numpy array.
- Parameters:
rst (str or pathlib.Path) – File path of the file, .rst arr.
return_bounds (bool, default False) – Flag to indicate whether the bounds of the arr should be returned.
- Returns:
arr (numpy.ndarray) – Array format of raster file.
profile (rasterio.profiles) – See
rasterio.profiles.Profilebounds (list) – List of bounds (xmin,ymin,xmax,ymax) if return_bounds is True
- pywatemsedem.geo.utils.mask_array_with_val(arr, mask, mask_val)[source]
Mask an array using a mask array.
- Parameters:
arr (numpy.ndarray) – Array of which values are masked.
mask (numpy.ndarray) – Masking array with same dimensions as arr.
mask_val (float or int) – Values in mask where arr should be masked.
- Returns:
Masked array where mask equals mask_val.
- Return type:
- pywatemsedem.geo.utils.nearly_identical(geoms, p, threshold=0.75)[source]
Identify nearly identical geometries
- Parameters:
geoms (geopandas.GeoSeries)
p (shapely.Geometry)
- Returns:
True/False
- Return type:
- pywatemsedem.geo.utils.points_to_raster(vct_point, rst_out, rst_template, field, dtype)[source]
Convert a point shapefile to a raster.
- Parameters:
vct_point (str or pathlib.Path) – File path of input point shapefile.
rst_out (str or pathlib.Path) – File path of output rasterfile.
rst_template (str or pathlib.Path) – File path to a template raster.
field (str) – The field of the shapefile containing the values for the raster.
dtype (str) – Data type of the values, e.g. Byte/Int16/UInt16/UInt32/Int32/Float32.
Notes
Uses and relies on saga_cmd CLI.
- pywatemsedem.geo.utils.polygons_to_raster(vct_polygon, rst_out, rst_template, field, dtype)[source]
Converts a polygon shapefile to a raster
- Parameters:
vct_polygon (str or pathlib.Path) – File path of input polygon shapefile
rst_out (str or pathlib.Path) – File path of output rasterfile
rst_template (str or pathlib.Path) – File path to a template raster
field (str) – The field of the shapefile containing the values for the raster
dtype (str, default None) – Data type of the values, e.g. Byte/Int16/UInt16/UInt32/Int32/Float32…
Note
Uses and relies on saga_cmd CLI
- pywatemsedem.geo.utils.process_mask_shape_from_raster_file(gdf_catchment, catchment_value=1)[source]
Process the geopandas shape format of the input raster
- Parameters:
gdf_catchment (geopandas.GeoDataFrame) – dataframe holding the mask , possible in multiple polygons (rows)
catchment_value (int, default 1) – value that is used to define catchment
- Returns:
gdf_catchment – dissolved dataframe holding mask, in one polygon (row)
- Return type:
- pywatemsedem.geo.utils.raster_array_to_pandas_dataframe(arr_raster, profile)[source]
Convert a raster array to a pandas dataframe.
- Parameters:
arr_raster (numpy.ndarray) – Array raster format
profile (rasterio.profiles) – See
rasterio.profiles.Profile
- Returns:
df – A pandas format of the array raster with
row (int): the row id
col (int): the column id
val (float): the value
- Return type:
- pywatemsedem.geo.utils.raster_dataframe_to_arr(df, profile, col, dtype)[source]
Convert a pandas dataframe column to an array
- Parameters:
df (pandas.DataFrame) –
A pandas format of the array raster with
row (int): the row id
col (int): the column id
val (float): the value
profile (rasterio.profiles) – See
rasterio.profiles.Profilecol (str) – Column name to convert to raster
dtype (numpy.dtype)
- Returns:
arr – Array of dataframe columns ‘val’
- Return type:
- pywatemsedem.geo.utils.raster_to_polygon(rst_in, vct_out)[source]
Polygonize a raster.
This function converts raster cells to polygons.
- Parameters:
rst_in (str or pathlib.Path) – File path of the input raster.
vct_out (str or pathlib.Path) – File path of the destination shapefile.
Notes
Uses and relies on saga_cmd CLI shapes_grid -6.
- pywatemsedem.geo.utils.rasterprofile_to_rstparams(profile)[source]
Transform rasterprofile to rstparams
- Parameters:
profile (rasterio.profiles) – See
rasterio.profiles.Profile- Returns:
rstparams – gdal dictionary holding all metadata for idrisi rasters
- Return type:
- pywatemsedem.geo.utils.read_rasterio_profile(rst_in)[source]
Read all spatial dimensions of a raster as a rasterio profile.
- Parameters:
rst_in (pathlib.Path) – File path to the input raster.
- Returns:
profile – See
pywatemsedem.geo.rasterproperties.RasterProperties.rasterio_profile().- Return type:
- pywatemsedem.geo.utils.read_rst_params(rst_in)[source]
Read all spatial dimensions of a raster.
- Parameters:
rst_in (pathlib.Path or str) – File path to the input raster.
- Returns:
minmax (list) – A list with the extreme coordinate values (xmin, ymin, xmax and ymax).
transform (rasterio.transform.Affine) – Transformation as defined in Rasterio.
cols (int) – The number of columns in the raster.
rows (int) – The number of rows in the raster.
- pywatemsedem.geo.utils.rst_to_vct_points(rst_in, vct_out)[source]
Convert all non-nodata values in a raster to a vector point file.
- Parameters:
rst_in (str or pathlib.Path) – File path of the raster file that should be converted to a shapefile.
vct_out (pathlib.Path) – File path of the destination vector.
- pywatemsedem.geo.utils.rstparams_to_rasterprofile(rstparams, epsg=None)[source]
Transform rstparams dictionary to rasterio raster profile dictionary
- Parameters:
- Returns:
profile – See
rasterio.profiles.Profile- Return type:
rasterio.profiles
- pywatemsedem.geo.utils.saga_intersection(vct_a, vct_b, vct_intersect)[source]
Calculate the intersection between two shapefiles
- Parameters:
vct_a (str or pathlib.Path) – File path of input shapefile 1
vct_b (str or pathlib.Path) – File path of input shapefile 2
vct_intersect (str or pathlib.Path) – File path of the calculated intersection shapefile
Note
Uses and relies on saga_cmd CLI
- pywatemsedem.geo.utils.set_dtype_arr_rst(arr, profile, dtype=None)[source]
Set dtype for a numpy array and update the raster profile
- Parameters:
arr (numpy.ndarray) – arr of a raster for which dtype has to be changed
profile (rasterio.profiles) – See
rasterio.profiles.Profiledtype (numpy.dtype, default None) – e.g. np.float64, np.float32, ..
- Returns:
arr (numpy.ndarray) – dtype-updated arr of a raster for which dtype has to be changed
profile (rasterio.profiles) – See
rasterio.profiles.Profilewith update dtype geo medata information
- pywatemsedem.geo.utils.set_no_data_arr(arr, arr_mask, nodata)[source]
Set no data to values to raster array outside mask.
- Parameters:
arr (numpy.ndarray) – To mask array
arr_mask (numpy.ndarray) – Mask array
nodata (float) – The no data value to set in input array
- pywatemsedem.geo.utils.set_no_data_rst(rst_in, rst_out, arr_bindomain, profile, dtype=None, nodata_val=-9999)[source]
Set all pixels of a raster outside the model domain equal to NoData
- Parameters:
rst_in (str) – File path of input raster to set no data values
rst_out (str) – File path of output raster with no data values
arr_bindomain (numpy.ndarray) – Array used to define domain nodata. In domain is equal to one, outside domain is equal to zero.
profile (rasterio.profiles) – See
rasterio.profiles.Profiledtype (numpy.dtype, default None) – e.g. np.float64, np.float32, …
nodata_val (int, default -9999) – Standard value for nodata
- pywatemsedem.geo.utils.tiff_to_geopandas_df(tiff_in)[source]
Transform a tiff file to a geopandas dataframe.
- Parameters:
tiff_in (str or pathlib.Path) – File path of tiff raster file.
- Returns:
Geopandas representation of tiff raster.
- Return type:
- pywatemsedem.geo.utils.tiff_to_idrisi(tiff_in, rst_out, dtype)[source]
Convert a GeoTiff to an Idrisi RST.
- Parameters:
tiff_in (pathlib.Path or str) – File path of the input tiff file.
rst_out (pathlib.Path or str) – File path of the destination rst.
dtype (str) – Raster type (e.g. “Float32”, “Int16”, “Int32”, “Int64”).
Notes
Uses and relies on gdal_translate CLI.
- pywatemsedem.geo.utils.valid_gdal_type(func)[source]
Check if input array mask is valid.
Use this function as a decorator.
- Parameters:
func (callable) – Function to wrap.
- Returns:
Wrapped function.
- Return type:
callable
- pywatemsedem.geo.utils.valid_mask(func)[source]
Check if your input array mask is valid. Use as decorator
- pywatemsedem.geo.utils.vct_to_rst_field(vct_in, rst_out, Cnst, field=None, alltouched=True, dtype='Float64')[source]
Rasterize a shapefile by a given attribute field.
- Parameters:
vct_in (str or pathlib.Path) – File path of the shapefile to be rasterized.
rst_out (pathlib.Path) – File path of the destination rst.
Cnst (dict) –
Dictionary with following keys:
res (int): resolution.
nodata (int): nodata flag.
minmax (list): list with xmin, ymin, xmax, ymax.
field (str, default None) – The field of the shapefile containing the values for the raster.
alltouched (bool, default True) – Enables the ALL_TOUCHED rasterization option so that all pixels touched by lines or polygons will be updated.
dtype (str, default "Float64") – Data type of the values, e.g. Byte/Int16/UInt16/UInt32/Int32/Float32.
Notes
Uses and relies on gdal_rasterize CLI.
- pywatemsedem.geo.utils.vct_to_rst_value(vct_in, rst_out, raster_properties, alltouched=True, dtype=None, gdal=True)[source]
Rasterize a shapefile by a given constant value.
- Parameters:
vct_in (str or pathlib.Path) – File path of the shapefile to be rasterized.
rst_out (pathlib.Path) – File path of the destination rst.
raster_properties (dict) –
Dictionary with following keys:
res (int): resolution.
nodata (int): nodata flag.
minmax (list): list with xmin, ymin, xmax, ymax.
alltouched (bool, default True) – Enables the ALL_TOUCHED rasterization option so that all pixels touched by lines or polygons will be updated.
dtype (str, default None) – Data type of the values, e.g. Byte/Int16/UInt16/UInt32/Int32/Float32.
gdal (bool, default True) – Rasterize using gdal_rasterize (True) or via saga CLI (False).
- pywatemsedem.geo.utils.vct_to_rst_value_gdal(vct_in, rst_out, raster_properties, nodata=-9999, alltouched=True, dtype=None)[source]
Rasterize a shapefile as data/no-data.
- Parameters:
vct_in (str or pathlib.Path) – File path of the shapefile to be rasterized.
rst_out (pathlib.Path) – File path of the destination rst.
raster_properties (dict) –
Dictionary with following keys:
res (int): resolution.
nodata (int): nodata flag.
minmax (list): list with xmin, ymin, xmax, ymax.
nodata (int, default -9999) – Nodata value.
alltouched (bool, default True) – Enables the ALL_TOUCHED rasterization option so that all pixels touched by lines or polygons will be updated.
dtype (str, default None) – Data type of the values, e.g. Byte/Int16/UInt16/UInt32/Int32/Float32.
Notes
Uses and relies on gdal_rasterize CLI.
- pywatemsedem.geo.utils.vct_to_rst_value_saga(vct_in, rst_out, raster_properties, alltouched=True, dtype=None)[source]
Rasterize a shapefile as data/no-data.
- Parameters:
vct_in (str or pathlib.Path) – File path of the shapefile to be rasterized.
rst_out (pathlib.Path) – File path of the destination rst.
raster_properties (dict) –
Dictionary with following keys:
res (int): resolution.
nodata (int): nodata flag.
minmax (list): list with xmin, ymin, xmax, ymax.
alltouched (bool, default True) – Enables the ALL_TOUCHED rasterization option so that all pixels touched by lines or polygons will be updated.
dtype (str, default None) – Data type of the values, e.g. Byte/Int16/UInt16/UInt32/Int32/Float32.
Notes
Uses and relies on saga_cmd CLI.
- pywatemsedem.geo.utils.write_arr_as_rst(arr, rst_out, dtype, profile)[source]
Write numpy.ndarray as a raster file.
- Parameters:
arr (numpy.ndarray) – 2D numpy array to be written as a raster file.
rst_out (pathlib.Path or str) – File path to the output raster.
dtype (numpy.dtype) – Data type for the output raster.
profile (dict) – Rasterio profile. See
rasterio.profiles.Profile.
- Raises:
pywatemsedem.geo.valid module
- exception pywatemsedem.geo.valid.PywatemsedemInputError[source]
Bases:
ExceptionRaise when input data are not conform the pywatemsedem required input format.
- exception pywatemsedem.geo.valid.PywatemsedemTypeError[source]
Bases:
ExceptionRaise when input data type don’t conform the pywatemsedem required type format.
- pywatemsedem.geo.valid.valid_exists(rst, fun)[source]
Check if input file exists
- Parameters:
rst (pathlib.Path) – File path to file, e.g. raster or vector.
fun (callable) – See
pywatemsedem.geo.valid.valid_input().
- pywatemsedem.geo.valid.valid_input(func=None, dict=None)[source]
Customizable wrapper function that allows to check arg-defined function input.
This wrapper is defined to check formats of file-based raster and vector input. It makes use of a dictionary to apply specific valid functions on non-keyword arguments. This valid function is typically applied to functions which have file paths that have to be checked in their input.
- Parameters:
func (callable) – To call function for which to check inputs. Note that only function with all keyword-arguments as parameters can be used.
dict (dictionary) – Holding string of fun parameters as keys, and valid-callable function as values.
- Return type:
function output
Examples
Use with a ‘@’-decorator to check input types for utils functions:
from pywatemsedem.geo.utils import ( valid_input, valid_rasterlist, valid_polygonvector ) #note: only on-keyword arguments! @valid_input(dict={"lst_rst": valid_rasterlist, "vct_in": valid_polygonvector}) def grid_statistics(lst_rst, vct_in): # ... function code
Above example checks if input of lst_rst is a list of rasters (and rasters exist) (1) and if input of vct_in is a polygoon shape (2).
Note
Can only be applied to non-keyword arguments.
Validation methods should be added to VALID_FUN.
- pywatemsedem.geo.valid.valid_linesvector(vct, fun)[source]
Check if input vector file is a valid lines shape
- Parameters:
vct (pathlib.Path) – File path to vector.
fun (callable) – See
pywatemsedem.geo.valid.valid_input().
- pywatemsedem.geo.valid.valid_mask(mask)[source]
Check if mask is not equal to none and valid
- Parameters:
mask
- pywatemsedem.geo.valid.valid_pointvector(vct, fun)[source]
Check if input vector file is a valid point shape
- Parameters:
vct (pathlib.Path) – File path to vector.
fun (callable) – See
pywatemsedem.geo.valid.valid_input().
- pywatemsedem.geo.valid.valid_polygonvector(vct, fun)[source]
Check if input vector file is a valid polygon shape
- Parameters:
vct (pathlib.Path) – File path to vector.
fun (callable) – See
pywatemsedem.geo.valid.valid_input().
- pywatemsedem.geo.valid.valid_raster(rst, fun)[source]
Check if input file is a valid raster
- Parameters:
rst (pathlib.Path) – File path to raster.
fun (callable) – See
pywatemsedem.geo.valid.valid_input().
- pywatemsedem.geo.valid.valid_rasterlist(lst_rst, fun)[source]
Check if input is a valid list of rasters
- Parameters:
lst_rst (list) – List of file paths to rasters.
fun (callable) – See
pywatemsedem.geo.valid.valid_input().
- pywatemsedem.geo.valid.valid_rp(rp)[source]
Check if rasterproperties is not equal to none and valid
- Parameters:
- pywatemsedem.geo.valid.valid_vector(vct, fun, req_type=None)[source]
Check if input file is a valid vector.
- Parameters:
vct (pathlib.Path) – File path to vector.
fun (callable) – See
pywatemsedem.geo.valid.valid_input().req_type (str, default None) – Required geometry type of vector, limited to “Polygon”, “LineString”, “Point” and None (i.e. don’t check).
- Returns:
True if valid.
- Return type:
- Raises:
IOError – If req_type is not a recognized geometry type.
PywatemsedemTypeError – If geometry type doesn’t match or file cannot be opened.
- pywatemsedem.geo.valid.valid_vectorlist(lst_vct, fun, req_type=None)[source]
Check if input is a valid list of rasters
- Parameters:
lst_vct (list) – List of file paths to rasters.
fun (callable) – See
pywatemsedem.geo.valid.valid_input().req_type – Required geometry type of vector. See
pywatemsedem.geo.valid.valid_vector()
Note
req_type can only be one type, not a mix.
pywatemsedem.geo.vectors module
- class pywatemsedem.geo.vectors.AbstractVector[source]
Bases:
objectAbstract vector class based on geopandas GeoDataFrame.
- geodata
Vector data.
- Type:
- check_crs(req_epsg)[source]
Check if CRS matches the required EPSG code.
- Parameters:
req_epsg (int) – Required EPSG code.
- check_if_empty()[source]
Check if input geodataframe is empty.
- Raises:
ValueError – If the geodataframe is empty.
- check_type(geometry_type, req_geometry, implemented_types=['LineString', 'Polygon', 'Point'])[source]
Check geometry types of vector to the required type.
- Parameters:
- Raises:
TypeError – If required geometry type is not implemented or does not match.
- property geodata
Return geodata.
- Returns:
Vector data.
- Return type:
- initialize(geodata, geometry_type, req_geometry_type=None, allow_empty=False, req_epsg=None)[source]
Initialize vector with geodata and geometry type.
- Parameters:
geodata (geopandas.GeoDataFrame) – Input data set.
geometry_type (str) – Geometry type of input dataset.
req_geometry_type (str, default None) – Geometry type, for implemented types, see
pywatemsedem.geo.vectors.AbstractVector.check_type().allow_empty (bool, default False) – Allow an empty geodataframe.
req_epsg (int, default None) – Required EPSG code.
- is_empty()[source]
Check if geodata (vector) is None (empty).
- Returns:
True if geodata is None, False otherwise.
- Return type:
- plot(color=None, column=None)[source]
Plot vector with geopandas plot.
- Parameters:
- Returns:
Axes object.
- Return type:
- rasterize(rst_reference, epsg, col='NR', nodata=None, dtype_raster='float', convert_lines_to_direction=False, gdal=False)[source]
Rasterize vector to array.
- Parameters:
rst_reference (str or pathlib.Path) – File path to reference file for raster output.
epsg (int) – EPSG code, should be a numeric value. See https://epsg.io/.
col (str, default "NR") – Column name to map.
nodata (float, default None) – Values within dataframe ‘col’ that have to be considered as nodata in raster.
dtype_raster (str, default "float") – Output raster type.
convert_lines_to_direction (bool, default False) – Convert lines to directions.
gdal (bool, default False) – Use gdal (True) or saga (False) engine for mapping.
- Returns:
Rasterized array.
- Return type:
- class pywatemsedem.geo.vectors.VectorFile(file_path, req_geometry_type=None, vct_clip=None, allow_empty=False, epsg=None)[source]
Bases:
AbstractVectorVector loaded from an input vector file.
- geodata
Vector data.
- Type:
- file_path
File path to input vector file.
- Type:
Notes
Inherits from
pywatemsedem.geo.vectors.AbstractVector.- clip(vct_clip)[source]
Clip input file path with vct_clip.
- Parameters:
vct_clip (pathlib.Path) – Mask vector.
- Returns:
Clipped geodataframe.
- Return type:
- class pywatemsedem.geo.vectors.VectorMemory(geodata, geometry_type, req_geometry_type=None, clip_mask=None, allow_empty=False, epsg=None)[source]
Bases:
AbstractVectorVector stored in memory from a geopandas GeoDataFrame.
- geodata
Vector data.
- Type:
Notes
Inherits from
pywatemsedem.geo.vectors.AbstractVector.- clip(geodata, clip_mask)[source]
Clip input geodata with clip_mask.
- Parameters:
geodata (geopandas.GeoDataFrame) – Geodataframe of input data.
clip_mask (geopandas.GeoDataFrame) – Mask vector.
- Returns:
Clipped geodataframe.
- Return type: