topotoolbox.GridObject#
- class topotoolbox.GridObject[source]#
Bases:
object
A class containing all information of a Digital Elevation Model (DEM).
Methods
__init__
()Initialize a GridObject instance.
aspect
([classify])Aspect returns the slope exposition of each cell in a digital elevation model in degrees.
curvature
([ctype, meanfilt])curvature returns the second numerical derivative (curvature) of a digital elevation model.
dilate
([size, footprint, structure])A simple wrapper around th scipy.ndimage.grey_dilation function, that also handles NaNs in the input GridObject.
erode
([size, footprint, structure])Apply a morphological erosion operation to the GridObject.
evansslope
([partial_derivatives, mode, modified])Evans method fits a second-order polynomial to 3x3 subgrids.
excesstopography
([threshold, method])Compute the two-dimensional excess topography using the specified method.
fillsinks
([bc, hybrid])Fill sinks in the digital elevation model (DEM).
filter
([method, kernelsize])The function filter is a wrapper around various image filtering algorithms.
gradient8
([unit, multiprocessing])Compute the gradient of a digital elevation model (DEM) using an 8-direction algorithm.
hillshade
([azimuth, altitude, exaggerate])Compute a hillshade of a digital elevation model
identifyflats
([raw, output])Identifies flats and sills in a digital elevation model (DEM).
info
()Prints all variables of a GridObject.
plot
([ax])Plot the GridObject
plot_hs
([ax, elev, azimuth, altitude, ...])Plot a shaded relief map of the GridObject
prominence
(tolerance[, use_hybrid])This function calculates the prominence of peaks in a DEM.
reproject
(crs[, resolution, resampling])Reproject GridObject to a new coordinate system.
shufflelabel
([seed])Randomize the labels of a GridObject
Attributes
The size of the second dimension of the grid
The dimensions of the grid in the correct order for libtopotoolbox
The size of the first dimension of the grid
Tuple of grid dimensions
- aspect(classify: bool = False) GridObject [source]#
Aspect returns the slope exposition of each cell in a digital elevation model in degrees. In contrast to the second output of gradient8 which returns the steepest slope direction, aspect returns the angle of the slope.
- Parameters:
classify (bool, optional) – directions are classified according to the scheme proposed by Gomez-Plaza et al. (2001), by default False
- Returns:
A GridObject containing the computed aspect data.
- Return type:
- property columns#
The size of the second dimension of the grid
- curvature(ctype='profc', meanfilt=False) GridObject [source]#
curvature returns the second numerical derivative (curvature) of a digital elevation model. By default, curvature returns the profile curvature (profc).
- Parameters:
ctype (str, optional) – What type of curvature will be computed, by default ‘profc’ - ‘profc’ : profile curvature [m^(-1)], - ‘planc’ : planform curvature [m^(-1))], - ‘tangc’ : tangential curvature [m^(-1)], - ‘meanc’ : mean curvature [m^(-1)], - ‘total’ : total curvature [m^(-2)]
meanfilt (bool, optional) – True if a mean filter will be applied before comuting the curvature, by default False
- Returns:
A GridObject storing the computed values.
- Return type:
- Raises:
ValueError – If wrong ctype has been used.
Examples
>>> dem = topotoolbox.load_dem('tibet') >>> curv = dem.curvature() >>> curv.show()
- dilate(size: tuple | None = None, footprint: ndarray | None = None, structure: ndarray | None = None) GridObject [source]#
A simple wrapper around th scipy.ndimage.grey_dilation function, that also handles NaNs in the input GridObject. Either size, footprint or structure has to be passed to this function. If nothing is provided, the function will raise an error.
- sizetuple of ints, optional
A tuple of ints containing the shape of the structuring element. Only needed if neither footprint nor structure is provided. Will result in a full and flat structuring element. Defaults to None
- footprintnp.ndarray of ints, optional
A array defining the footprint of the erosion operation. Non-zero elements define the neighborhood over which the erosion is applied. Defaults to None
- structurenp.ndarray of ints, optional
A array defining the structuring element used for the erosion. This defines the connectivity of the elements. Defaults to None
- Returns:
A GridObject storing the computed values.
- Return type:
- Raises:
ValueError – If size, structure and footprint are all None.
- property dims#
The dimensions of the grid in the correct order for libtopotoolbox
- erode(size: tuple | None = None, footprint: ndarray | None = None, structure: ndarray | None = None) GridObject [source]#
Apply a morphological erosion operation to the GridObject. Either size, footprint or structure has to be passed to this function. If nothing is provided, the function will raise an error.
- Parameters:
size (tuple of ints) – A tuple of ints containing the shape of the structuring element. Only needed if neither footprint nor structure is provided. Will result in a full and flat structuring element. Defaults to None
footprint (np.ndarray of ints, optional) – A array defining the footprint of the erosion operation. Non-zero elements define the neighborhood over which the erosion is applied. Defaults to None
structure (np.ndarray of ints, optional) – A array defining the structuring element used for the erosion. This defines the connectivity of the elements. Defaults to None
- Returns:
A GridObject storing the computed values.
- Return type:
- Raises:
ValueError – If size, structure and footprint are all None.
- evansslope(partial_derivatives: bool = False, mode: str = 'nearest', modified: bool = False) GridObject | Tuple[GridObject, GridObject] [source]#
Evans method fits a second-order polynomial to 3x3 subgrids. The parameters of the polynomial are the partial derivatives which are used to calculate the surface slope = sqrt(Gx**2 + Gy**2).
Evans method approximates the surface by regression surfaces. Gradients are thus less susceptible to noise in the DEM.
- Parameters:
mode (str, optional) – The mode parameter determines how the input DEM is extended beyond its boundaries: [‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’, ‘grid-mirror’, ‘grid-constant’, ‘grid-wrap’]. See scipy.ndimage.convolve for more information, by default ‘nearest’
modified (bool, optional) – If True, the surface is weakly smoothed before gradients are calculated (see Shary et al., 2002), by default False
partial_derivatives (bool, optional) – If True, both partial derivatives [fx, fy] will be returned as GridObjects instead of just the evansslope, by default False
- Returns:
A GridObject containing the computed evansslope data.
- Return type:
- excesstopography(threshold: float | int | ndarray | GridObject = 0.2, method: str = 'fsm2d') GridObject [source]#
Compute the two-dimensional excess topography using the specified method.
- Parameters:
threshold (float, int, GridObject, or np.ndarray, optional) – Threshold value or array to determine slope limits, by default 0.2. If a float or int, the same threshold is applied to the entire DEM. If a GridObject or np.ndarray, it must match the shape of the DEM.
method (str, optional) –
Method to compute the excess topography, by default ‘fsm2d’. Options are:
’fsm2d’: Uses the fast sweeping method.
’fmm2d’: Uses the fast marching method.
- Returns:
A new GridObject with the computed excess topography.
- Return type:
- Raises:
ValueError – If method is not one of [‘fsm2d’, ‘fmm2d’]. If threshold is an np.ndarray and doesn’t match the shape of the DEM.
TypeError – If threshold is not a float, int, GridObject, or np.ndarray.
- fillsinks(bc: ndarray | GridObject | None = None, hybrid: bool = True) GridObject [source]#
Fill sinks in the digital elevation model (DEM).
- Parameters:
bc (ndarray or GridObject, optional) – Boundary conditions for sink filling. bc should be an array of np.uint8 that matches the shape of the DEM. Values of 1 indicate pixels that should be fixed to their values in the original DEM and values of 0 indicate pixels that should be filled.
hybrid (bool, optional) – Should hybrid reconstruction algorithm be used? Defaults to True. Hybrid reconstruction is faster but requires additional memory be allocated for a queue.
- Returns:
The filled DEM.
- Return type:
- filter(method: str = 'mean', kernelsize: int = 3) GridObject [source]#
The function filter is a wrapper around various image filtering algorithms. Only filters with rectangular kernels of uneven dimensions are supported.
- Parameters:
method (str, optional) – Which method will be used to filter the DEM: [‘mean’, ‘average’, ‘median’, ‘sobel’, ‘scharr’, ‘wiener’, ‘std’], by default ‘mean’
kernelsize (int, optional) – Size of the kernel that will be applied. Note that [‘sobel’, ‘scharr’] require that the kernelsize is 3, by default 3
- Returns:
The filtered DEM as a GridObject.
- Return type:
- Raises:
ValueError – If the kernelsize does not match the requirements of this function or the selected method is not implemented in the function.
- gradient8(unit: str = 'tangent', multiprocessing: bool = True)[source]#
Compute the gradient of a digital elevation model (DEM) using an 8-direction algorithm.
- Parameters:
unit (str, optional) – The unit of the gradient to be calculated. Options are: - ‘tangent’ : Calculate the gradient as a tangent (default). - ‘radian’ : Calculate the gradient in radians. - ‘degree’ : Calculate the gradient in degrees. - ‘sine’ : Calculate the gradient as the sine of the angle. - ‘percent’ : Calculate the gradient as a percentage.
multiprocessing (bool, optional) – If True, use multiprocessing for computation. Default is True.
- Returns:
A new GridObject with the calculated gradient.
- Return type:
- hillshade(azimuth: float = 315.0, altitude: float = 60.0, exaggerate: float = 1.0)[source]#
Compute a hillshade of a digital elevation model
- Parameters:
azimuth (float) – The azimuth angle of the light source measured in degrees clockwise from north. Defaults to 315 degrees.
altitude (float) – The altitude angle of the light source measured in degrees above the horizon. Defaults to 60 degrees.
exaggerate (float) – The amount of vertical exaggeration. Increase to emphasize elevation differences in flat terrain. Defaults to 1.0
- Returns:
A GridObject containing the resulting hillshade data
- Return type:
- identifyflats(raw: bool = False, output: list[str] | None = None) tuple [source]#
Identifies flats and sills in a digital elevation model (DEM).
- Parameters:
raw (bool, optional) – If True, returns the raw output grid as np.ndarray. Defaults to False.
output (list of str, optional) – List of strings indicating desired output types. Possible values are ‘sills’, ‘flats’. Order of inputs in list are irrelevant, first entry in output will always be sills. Defaults to [‘sills’, ‘flats’].
- Returns:
A tuple containing copies of the DEM with identified flats and/or sills.
- Return type:
tuple
Notes
Flats are identified as 1s, sills as 2s, and presills as 5s (since they are also flats) in the output grid. Only relevant when using raw=True.
- plot(ax=None, **kwargs)[source]#
Plot the GridObject
- Parameters:
ax (matplotlib.axes.Axes, optional) – The axes in which to plot the GridObject. If no axes are given, the current axes are used.
**kwargs – Additional keyword arguments are forwarded to matplotlib.axes.Axes.imshow
- Returns:
The image constructed by imshow
- Return type:
matplotlib.image.AxesImage
- plot_hs(ax=None, elev=None, azimuth=315, altitude=60, exaggerate=1, filter_method=None, filter_size=3, cmap='terrain', norm=None, blend_mode='soft', **kwargs)[source]#
Plot a shaded relief map of the GridObject
- Parameters:
ax (matplotlib.axes.Axes, optional) – The axes in which to plot the GridObject. If no axes are given, the current axes are used.
elev (GridObject, optional) – The digital elevation model used for shading. If no DEM is provided, the data GridObject is also used for shading.
azimuth (float, optional) – The azimuth angle of the light source in degrees from North. Defaults to 315 degrees.
altitude (float, optional) – The altitude angle of the light source in degrees above the horizon. Defaults to 60 degrees.
exaggerate (float, optional) – The amount of vertical exaggeration to apply to the elevation. Defaults to 1.
filter_method ('str', optional) – The method used to filter the DEM before computing the hillshade. The data GridObject is not filtered. This should be one of the methods provided by GridObject.filter. Defaults to None, which does not apply a filter.
filter_size (int, optional) – The size of the filter kernel in pixels. Defaults to 3.
cmap (colors.Colormap or str or None) – The colormap to use in coloring the data. Defaults to ‘terrain’.
norm (colors.Normalize, optional) – The normalization method that scales the color data to the [0,1] interval. Defaults to a linear scaling from the minimum of the data to the maximum.
blend_mode ({'multiply', 'overlay', 'soft'}, optional) – The algorithm used to combine the shaded elevation with the data. Defaults to ‘soft’.
**kwargs – Additional keyword arguments are forwarded to matplotlib.axes.Axes.imshow
- Returns:
The image constructed by imshow
- Return type:
matplotlib.image.AxesImage
- Raises:
TypeError – The elev argument is not a GridObject
ValueError – The elev argument is not the same shape as the data
ValueError – A blend_mode other than ‘multiply’, ‘overlay’ or ‘soft’ is provided.
ValueError – The filter_method or filter_size arguments are not accepted by GridObject.filter.
- prominence(tolerance: float, use_hybrid=True) Tuple [source]#
This function calculates the prominence of peaks in a DEM. The prominence is the minimal amount one would need to descend from a peak before being able to ascend to a higher peak. The function uses image reconstruct (see function imreconstruct) to calculate the prominence. It may take a while to run for large DEMs. The algorithm iteratively finds the next higher prominence and stops if the prominence is less than the tolerance, the second input parameter to the function.
- Parameters:
tolerance (float) – The minimum tolerance for the second to last found peak. (meters) Will always find one peak.
use_hybrid (bool, optional) – If True, use the hybrid reconstruction algorithm. Defaults to True.
- Returns:
A Tuple containing a ndarray storing the computed prominence and a tuple of ndarray. Each array in the inner tuple has the same shape as the indices array (as returned by np.unravel_index).
- Return type:
Tuple[np.ndarray, Tuple]
- reproject(crs: CRS, resolution: float | None = None, resampling: Resampling = Resampling.bilinear)[source]#
Reproject GridObject to a new coordinate system.
- Parameters:
crs (rasterio.CRS) – Target coordinate system
resolution (float, optional) – Target resolution. If one is not provided, a resolution that approximately matches that of the source coordinate system will be used.
resampling (rasterio.enums.Resampling, optional) – Resampling method. The default is bilinear resampling.
- Returns:
The reprojected data.
- Return type:
- property rows#
The size of the first dimension of the grid
- property shape#
Tuple of grid dimensions
- shufflelabel(seed=None)[source]#
Randomize the labels of a GridObject
This function is helpful when plotting drainage basins. It will work with any kind of data, but is most useful when given ordinal data such as an integer-valued GridObject.
- Parameters:
seed (optional) –
The seed used to generate the random permutation of labels.
The seed is passed directly to numpy.random.default_rng.
- Returns:
A grid identical to the input, but with randomly reassigned labels.
- Return type: