pydsstools.core.raster_grid

Functions

guard_vector_mask(feat)

Transform feat to polygon feature if does not have __geo_interface__ attribute

shapefile_to_shapes(shape_file)

Classes

RasterSpatialGrid(ds, **kwargs)

Lightweight raster wrapper around an in-memory rasterio dataset.

VectorShape(shell[, holes])

class pydsstools.core.raster_grid.RasterSpatialGrid(ds, **kwargs)[source]

Bases: object

Lightweight 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 to SpatialGridStruct, but backed by a rasterio dataset instead of a DSS/structured grid.

classmethod from_file(path, **kwargs)[source]

Open a raster file and return a RasterSpatialGrid instance.

The instance owns the underlying dataset and should be closed when no longer needed — either via close() or as a context manager.

Parameters:
  • path (str or path-like) – Path to any raster format supported by rasterio (GeoTIFF, GRIB, HDF5, etc.).

  • **kwargs – Passed through to __init__() (e.g. grid_type, data_units, data_type).

Return type:

RasterSpatialGrid

close()[source]

Close the underlying dataset if this instance owns it.

read(masked=False)[source]

Read raster data from band 1.

Parameters:

masked (bool, default False) – If True, return a numpy.ma.MaskedArray where pixels equal to the band nodata value are masked. If False, return a plain numpy.ndarray.

Returns:

2D array of raster values for band 1, always as float32. If the underlying dataset is already stored as float32, no copy is made.

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. dtype is always reported as float32. When the underlying dataset has no nodata value set, UNDEFINED is used.

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 a component 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 height key in the dataset profile.

Type:

int

property cols

Number of columns (width) in the raster.

Equivalent to the width key in the dataset profile.

Type:

int

property width

Raster width in pixels.

Alias for cols.

Type:

int

property height

Raster height in pixels.

Alias for rows.

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:

DataType

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:

GridType

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:

GridInfoBase

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 ax is 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 ax is supplied or colorbar is False, the function

    only draws the image and does not create a colorbar.

save_tiff(filepath)[source]

Save the raster to a GeoTIFF file.

Parameters:

filepath (str or path-like) – Path of the output GeoTIFF file. Must have a .tif or .tiff extension.

Raises:

ValueError – If filepath does not have a .tif or .tiff extension.

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 RasterSpatialGrid instance with resampled data.

Return type:

RasterSpatialGrid

Raises:

NotImplementedError – If called on HRAP or HRAP-time grids, where resampling is explicitly not implemented.

reproject(dst_crs, method=None, cell_size=None, unit_factor=None, data_units=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.

  • cell_size (float or tuple, optional) – Target pixel size (in units of dst_crs). If None, a default resolution is chosen by rasterio.warp.calculate_default_transform().

  • unit_factor (float, optional) – Multiplicative factor applied to source values before reprojection (e.g., 3600 to convert in/sec to in/hour). Nodata pixels are preserved. When supplied, output dtype is promoted to float32 to avoid integer overflow or truncation; the source nodata sentinel is carried over unchanged. Must be paired with data_units.

  • data_units (str, optional) – Data units to assign to the returned grid. Required when unit_factor is supplied, since scaling values changes their units. When omitted, the source grid’s data_units are carried over unchanged.

Returns:

New RasterSpatialGrid instance in the target CRS, with appropriately sized output grid and transform.

Return type:

RasterSpatialGrid

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 new RasterSpatialGrid instance.

Parameters:
  • poly (str, list, tuple, object) – Shapefile path, any geometry implementing __geo_interface__, list/tuple of such geometries, or a BoundingBox.

  • 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_width pixels.

  • pad_width (int or float, default 0) – Number of pixels (or map units, depending on rasterio version) to pad the cropped extent.

Returns:

New RasterSpatialGrid with masked data and updated transform and dimensions.

Return type:

RasterSpatialGrid

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 None if GDAL/OGR is not available.

Return type:

osgeo.ogr.DataSource or None

Notes

  • The output shapefile contains a MultiLineString layer with

    attributes ID (integer) and ELEV (real).

  • This method uses gdal.ContourGenerate() under the hood.