UrbanAccessAnalyzer.raster_ops¶
Raster I/O, reprojection, rasterization/vectorization, and DEM tools.
This is the raster-side counterpart to :mod:UrbanAccessAnalyzer.geometry_ops.
Raster processing stays on rasterio/scipy.ndimage/skimage --
these are the correct, mature tools for grid data and there is no
polars-native raster representation to migrate to. The one interface change
from the previous raster_utils.py is :func:vectorize, which now returns
a Polars DataFrame with a WKB geometry column instead of a GeoDataFrame,
so it composes directly with :mod:UrbanAccessAnalyzer.h3_ops /
:mod:UrbanAccessAnalyzer.geometry_ops without an intermediate geopandas
round-trip.
Also folds in DEM-specific helpers (:func:download_dem, :func:contours,
previously dem_tools.py) since they are thematically raster I/O and were
otherwise an orphan two-function module.
Sources:
- OpenTopography Global DEM API: https://portal.opentopography.org/apidocs/#/Public/getGlobalDem
- rasterio reprojection/masking: https://rasterio.readthedocs.io
validate_crs(src)
¶
The CRS of a raster source, dict, CRS, string or EPSG code, as a rasterio CRS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
DatasetReader | DatasetWriter | dict | CRS | str | int
|
An open rasterio dataset, a profile dict, a |
required |
Returns:
| Type | Description |
|---|---|
|
The rasterio |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no CRS can be read. |
extract_affine_params(transform)
¶
Extracts the six affine transformation parameters (a, b, c, d, e, f).
This utility handles both rasterio.Affine objects and 3x3 NumPy arrays, which are common ways to represent affine transformations in GIS workflows.
The affine transformation maps pixel coordinates (col, row) to map coordinates (x, y) as follows: x = a * col + b * row + c y = d * col + e * row + f
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transform
|
Affine or ndarray
|
The input affine transformation. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
Tuple[float, float, float, float, float, float]
|
A tuple of six float values: (a, b, c, d, e, f). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the transform format is not a rasterio.Affine or a 3x3 NumPy array. |
reproject(data, transform, crs, src_nodata=None, dst_nodata=np.nan, dst_transform=None, dst_crs='utm', width=None, height=None)
¶
Reprojects a raster to its local UTM zone while preserving the pixel grid. Returns float64 array with dst_nodata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
Raster values (2-D). |
required |
transform
|
Affine
|
Affine transform of |
required |
crs
|
CRS
|
CRS of |
required |
src_nodata
|
Optional[Union[int, float]]
|
Nodata value of |
None
|
dst_nodata
|
Optional[float]
|
Nodata value of the output. |
nan
|
dst_transform
|
Output transform; |
None
|
|
dst_crs
|
Optional[Union[CRS, int, str]]
|
Output CRS; |
'utm'
|
width
|
int | None
|
Output width in pixels. |
None
|
height
|
int | None
|
Output height in pixels. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, Affine, CRS]
|
|
reproject_global(data, transform, crs, src_nodata=None, dst_nodata=np.nan, dst_crs='EPSG:3857', resolution=1000.0)
¶
Reprojects a raster to a fixed global Web Mercator grid, ensuring perfect alignment with other rasters reprojected this way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
Source raster array. |
required |
transform
|
Affine
|
Source affine transform. |
required |
crs
|
CRS
|
Source CRS. |
required |
src_nodata
|
int | float
|
Source nodata value. |
None
|
dst_nodata
|
float
|
Destination nodata value. |
nan
|
dst_crs
|
CRS / int / str
|
Target CRS (default EPSG:3857). |
'EPSG:3857'
|
resolution
|
float
|
Pixel size in target CRS units (default 1000 meters). |
1000.0
|
Returns:
| Name | Type | Description |
|---|---|---|
ndarray
|
np.ndarray: Reprojected raster array. |
|
Affine |
Affine
|
Destination affine transform. |
CRS |
CRS
|
Destination CRS. |
raster_crop(src_input, aoi=None, nodata=np.nan, projected=False)
¶
Read a raster (path or open dataset), crop it to an area and optionally reproject it to UTM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_input
|
Union[str, Path, DatasetReader]
|
Raster path or open rasterio dataset. |
required |
aoi
|
Optional[Union[GeoDataFrame, GeoSeries]]
|
Area to crop to; |
None
|
nodata
|
float | None
|
Value written for nodata pixels. |
nan
|
projected
|
bool
|
Reproject to the local UTM zone. |
False
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, Affine, CRS, int, int]
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the path does not exist. |
read_raster(path, aoi=None, nodata=np.nan, projected=False)
¶
Reads a raster from a given path, optionally crops it to an AOI, and reprojects it to UTM if its native CRS is geographic. The output raster data will always be of float64 dtype with np.nan representing nodata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Path to the GeoTIFF raster file. |
required |
aoi
|
Optional[Union[GeoDataFrame, GeoSeries]]
|
Area of Interest to crop the raster. If None, the entire raster is processed. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, Affine, CRS]
|
Tuple[np.ndarray, Affine, CRS]: A tuple containing: - data (np.ndarray): The raster data (cropped, reprojected, float64, nan for nodata). - transform (Affine): The affine transform of the output raster. - crs (CRS): The CRS of the output raster (UTM if source was geographic). |
vectorize(raster_array, transform, crs, aoi=None, keep_nodata=False, nodata=None)
¶
Vectorizes a raster numpy array (float, int, or str), returning a Polars DataFrame of pixel polygons (WKB, EPSG:4326) with their corresponding raster values.
Nodata handling rules: - float arrays: nodata defaults to np.nan - int arrays: nodata can be np.nan (array cast to float internally) - str arrays: nodata defaults to np.nan, BUT '' is always treated as nodata regardless
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_array
|
ndarray
|
The input raster data array. Can be float, int, or str. |
required |
transform
|
Affine
|
The affine transform of the raster_array. |
required |
crs
|
CRS
|
The CRS of the raster_array. |
required |
aoi
|
Optional[GeoDataFrame | GeoSeries]
|
Area of interest. If provided, only pixels intersecting the AOI are included. |
None
|
keep_nodata
|
bool, default=False
|
If True, nodata pixels (NaN, explicit nodata, or '') are included with value=None. |
False
|
nodata
|
float | int | str
|
Explicit nodata value (overrides defaults, except '' is always nodata for str). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
gpd.GeoDataFrame: GeoDataFrame with columns: - 'id': unique pixel identifier - 'geometry': pixel polygon in EPSG:4326 - 'value': raster value or None |
download_dem(dem_key, aoi, path, dem_type='COP30', overwrite=False)
¶
Download a DEM from the OpenTopography Global DEM API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dem_key
|
str
|
OpenTopography API key. See https://opentopography.org/blog/introducing-api-keys-access-opentopography-global-datasets |
required |
aoi
|
Union[GeoSeries, GeoDataFrame]
|
Area of interest; its total bounds (reprojected to EPSG:4326) define the download extent. |
required |
path
|
str
|
Destination file path, or a directory (in which case
|
required |
dem_type
|
str
|
DEM product, e.g. |
'COP30'
|
overwrite
|
bool
|
Re-download even if |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Tuple |
Affine
|
GeoTIFF. |
Raises:
| Type | Description |
|---|---|
Exception
|
If the OpenTopography request fails. |
contours(dem, height, transform, crs, min_pixels=0)
¶
Extract polygons of DEM area above a given elevation threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dem
|
ndarray
|
2D elevation array (may contain NaN). |
required |
height
|
float
|
Elevation threshold (same units as |
required |
transform
|
Affine
|
Affine transform of |
required |
crs
|
CRS of |
required | |
min_pixels
|
int
|
Minimum pixel count for a contour polygon to be kept (filters small islands more robustly than an area threshold when pixel size varies). |
0
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame of polygons where |
GeoDataFrame
|
column. |
rasterize(gdf, transform, shape, crs, value_column=None, value_order=None, background_value=0, all_touched=True)
¶
Rasterize a GeoDataFrame into a numpy array using a given raster transform and shape. Supports int, float, or str rasters. Automatically handles value_order priority and string categorical rasters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
Geometries to burn. |
required |
transform
|
Affine
|
Affine transform of the output grid. |
required |
shape
|
tuple[int, int]
|
|
required |
crs
|
CRS of the output grid (the geometries are reprojected to it). |
required | |
value_column
|
Optional[str]
|
Column burnt into the pixels; |
None
|
value_order
|
Optional[List[Union[int, float, str]]]
|
Values from highest to lowest priority where geometries overlap. |
None
|
background_value
|
Union[int, float, str]
|
Value of pixels with no geometry. |
0
|
all_touched
|
bool
|
Burn every pixel a geometry touches (not only those whose centre it covers). |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The raster array. |
buffer_mean(raster, transform, buffer=0, kernel_shape='disk')
¶
Calculates the density of values in a raster.
The input raster is expected to be in a metric (UTM) CRS.
Density is calculated as value / area. If a buffer is specified,
a moving window average is applied using a circular kernel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster
|
ndarray
|
The input raster data array (e.g., population counts). Expected to be in a metric CRS. |
required |
transform
|
Affine
|
The affine transform of the raster. |
required |
buffer
|
float
|
Radius of the buffer in meters for density calculation. If 0, density is calculated per pixel. If > 0, a moving average is computed over a circular window of this radius. Defaults to 0. |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A numpy array representing the density raster (e.g., population density per km²). |
merge(input_paths, bounds=None, method='max')
¶
Mosaic several rasters into one, optionally limited to bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_paths
|
Raster paths or open rasterio datasets. |
required | |
bounds
|
GeoSeries
|
Optional area; the mosaic covers its bounding box. |
None
|
method
|
How overlapping pixels combine ( |
'max'
|
Returns:
| Type | Description |
|---|---|
|
|