pydsstools.core.raster_grid
Functions
|
Transform feat to polygon feature if does not have __geo_interface__ attribute |
|
Classes
|
Lightweight raster wrapper around an in-memory rasterio dataset. |
|
- class pydsstools.core.raster_grid.RasterSpatialGrid(ds, **kwargs)[source]
Bases:
objectLightweight raster wrapper around an in-memory rasterio dataset.
This class provides a raster-like interface on top of a rasterio dataset, exposing common properties (transform, bounds, cell size, CRS, nodata) and methods for:
Reading data as a NumPy or masked array.
Plotting with matplotlib.
Resampling within the same CRS.
Reprojecting to a new CRS.
Masking with vector geometries (via
rasterio.mask).Exporting the grid to a GeoTIFF.
Generating contour shapefiles using GDAL.
Instances are usually created via
RasterAccessor.inst()and are intended to behave similarly toSpatialGridStruct, but backed by a rasterio dataset instead of a DSS/structured grid.- read(masked=False)[source]
Read raster data from band 1.
- Parameters:
masked (bool, default False) – If True, return a
numpy.ma.MaskedArraywhere pixels equal to the band nodata value are masked. If False, return a plainnumpy.ndarray.- Returns:
2D array of raster values for band 1.
- Return type:
ndarray or numpy.ma.MaskedArray
- get_extents()[source]
Compute bounding coordinates of the raster in map units.
- Returns:
(xmin, xmax, ymin, ymax) in the dataset CRS.
- Return type:
tuple of float
- get_min_xy()[source]
Return the minimum (x, y) coordinates of the raster bounds.
- Returns:
(xmin, ymin) in the dataset CRS.
- Return type:
tuple of float
- property profile
Rasterio dataset metadata profile.
Includes driver, dtype, crs, transform, width, height, etc.
- Type:
dict
- property transform
Affine transformation matrix.
Maps pixel coordinates to map coordinates in the dataset CRS.
- Type:
Affine
- property cell_size
Cell size (pixel width) in map units.
Extracted from the
acomponent of the affine transform.- Type:
float
- property bounds
Bounding box in map coordinates.
Returns (xmin, ymin, xmax, ymax) computed from the transform and grid dimensions.
- Type:
BoundingBox
- property rows
Number of rows (height) in the raster.
Equivalent to the
heightkey in the dataset profile.- Type:
int
- property cols
Number of columns (width) in the raster.
Equivalent to the
widthkey in the dataset profile.- Type:
int
- property crs
Coordinate reference system as WKT string.
Converted from the rasterio CRS object in the dataset profile.
- Type:
str
- property nodata
NoData value for missing/invalid pixels.
Read from the dataset profile.
- Type:
float
- property data_units
Physical units of the data (e.g., “MM”, “M”, “CFS”).
Provided at construction via keyword arguments.
- Type:
str
- property data_type
Temporal aggregation type (per_aver, inst_val, etc.).
Provided at construction via keyword arguments.
- Type:
- property grid_type
Grid type inferred from CRS or explicitly set.
If grid_type was provided at construction, returns that value. Otherwise, infers from CRS: HRAP projection returns hrap_time, equal-area conic returns albers_time, other CRS returns specified_time, and missing CRS returns undefined_time.
- Type:
- property gridinfo
Grid metadata object (GridInfo, HrapInfo, AlbersInfo, or SpecifiedInfo).
Creates and returns the appropriate GridInfo subclass based on grid_type, with coordinates normalized from the raster transform.
- Type:
- gridinfo_dict()[source]
Build a dictionary of grid metadata for GridInfoCreate.
- Returns:
Dictionary containing grid_type, shape, data_units, data_type, cols, rows, cell_size, nodata, and crs.
- Return type:
dict
- plot(**kwargs)[source]
Plot the raster using rasterio.plot.show with optional colorbar.
- Parameters:
mask_zeros (bool, default False) – If True, cells equal to 0 are also treated as missing and plotted as transparent (NaN).
colorbar (bool, default True) – If True, draw a colorbar using matplotlib. Ignored when an external
axis provided.cmap (str, default "Spectral") – Matplotlib colormap name.
**kwargs – Additional keyword arguments are passed through to
rasterio.plot.show().
Notes
- The underlying data are read as a masked array; existing nodata
pixels are converted to NaN for plotting.
- When
axis supplied orcolorbaris False, the function only draws the image and does not create a colorbar.
- When
- save_tiff(filepath)[source]
Save the raster to a GeoTIFF file.
- Parameters:
filepath (str or path-like) – Path of the output GeoTIFF file. The current dataset profile (including CRS, transform, dtype, nodata) is preserved.
- resample(scale, method=None, memory=64)[source]
Resample the raster by a uniform scale factor in x and y.
- Parameters:
scale (float) – Scale factor for pixel size. Values > 1 coarsen the grid (larger pixels, fewer rows/cols); values < 1 refine it.
method (rasterio.enums.Resampling, default Resampling.bilinear) – Resampling algorithm to use (nearest, bilinear, cubic, etc.).
memory (int, default 64) – Approximate warp memory limit in megabytes passed to
rasterio.warp.reproject().
- Returns:
New
RasterSpatialGridinstance with resampled data.- Return type:
- Raises:
NotImplementedError – If called on HRAP or HRAP-time grids, where resampling is explicitly not implemented.
- reproject(dst_crs, method=None, cellsize=None)[source]
Reproject the raster to a new CRS.
- Parameters:
dst_crs (Any) – Target CRS, in any form accepted by rasterio (e.g., WKT, PROJ string, EPSG code, or dict).
method (rasterio.enums.Resampling, default Resampling.nearest) – Resampling algorithm to use during reprojection.
cellsize (float or tuple, optional) – Target pixel size (in units of
dst_crs). If None, a default resolution is chosen byrasterio.warp.calculate_default_transform().
- Returns:
New
RasterSpatialGridinstance in the target CRS, with appropriately sized output grid and transform.- Return type:
- mask(poly, all_touched=False, invert=False, filled=True, crop=False, pad=False, pad_width=0)[source]
Mask the raster using vector geometries and return a new grid.
This is a thin wrapper around
rasterio.mask.mask()that accepts a variety of geometry inputs and returns a newRasterSpatialGridinstance.- Parameters:
poly (str, list, tuple, object) – Shapefile path, any geometry implementing
__geo_interface__, list/tuple of such geometries, or aBoundingBox.all_touched (bool, default False) – If True, all pixels touched by geometries will be included in the mask; otherwise only pixels whose center is within the polygon are used.
invert (bool, default False) – If True, mask the pixels inside the shapes instead of outside.
filled (bool, default True) – If True, return an ndarray with masked pixels set to the dataset nodata value. If False, return a masked array.
crop (bool, default False) – If True, crop the output to the extent of the shapes.
pad (bool, default False) – If True, pad the cropped extent by
pad_widthpixels.pad_width (int or float, default 0) – Number of pixels (or map units, depending on rasterio version) to pad the cropped extent.
- Returns:
New
RasterSpatialGridwith masked data and updated transform and dimensions.- Return type:
- generate_contours(shape_file, **kwargs)[source]
Generate contour lines and save them as a shapefile using GDAL.
- Parameters:
shape_file (str or path-like) – Path of the output contour shapefile.
base (float, default 0) – Base elevation relative to which contour intervals are generated.
interval (float, default 10) – Elevation interval between successive contour lines.
fixed_levels (list of float, default []) – Additional specific elevations at which contours are generated, in addition to the regular interval.
ignore_nodata (bool, default True) – If True, pixels equal to the nodata value are ignored during contour generation.
- Returns:
OGR datasource for the created shapefile, or
Noneif GDAL/OGR is not available.- Return type:
osgeo.ogr.DataSource or None
Notes
- The output shapefile contains a
MultiLineStringlayer with attributes
ID(integer) andELEV(real).
- The output shapefile contains a
This method uses
gdal.ContourGenerate()under the hood.