GIS data I/O
The GIS I/O module provides functions for reading geospatial data in various formats, including raster (GeoTIFF) and vector (Shapefile) files.
Overview
MOBIDICpy uses industry-standard libraries for geospatial data handling:
- Rasterio for raster data (GeoTIFF)
- GeoPandas for vector data (Shapefiles, GeoJSON, etc.)
All functions provide comprehensive logging and error handling, converting nodata values to NaN for consistent numerical processing.
Functions
Raster I/O
mobidic.preprocessing.gis_reader.grid_to_matrix(gridname)
Read raster grid file and return data array with corner coordinates. This function replicates the behavior of MATLAB’s function for GeoTIFF files.
Reads raster files in GeoTIFF (.tif, .tiff) format. Returns the data array and corner coordinates adjusted to cell centers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gridname
|
str | Path
|
Path to the grid file (.tif, .tiff). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing: - ‘data’: 2D numpy array with raster values (NaN for nodata) - ‘xllcorner’: X coordinate of lower-left corner (cell center) - ‘yllcorner’: Y coordinate of lower-left corner (cell center) - ‘cellsize’: Cell size in map units |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the grid file does not exist. |
ValueError
|
If the file format is not supported. |
RuntimeError
|
If there are errors reading the file. |
Notes
- Corner coordinates are adjusted to cell centers (0.5 * cellsize offset)
- Data is flipped vertically to match MATLAB convention
- Very small values (< -1e32) are converted to NaN
Examples:
>>> result = grid_to_matrix('elevation.tif')
>>> data = result['data']
>>> print(f"Shape: {data.shape}, Resolution: {result['cellsize']}m")
Source code in mobidic/preprocessing/gis_reader.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
Vector I/O
mobidic.preprocessing.gis_reader.read_shapefile(filepath, crs=None)
Read a shapefile and return a GeoDataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the shapefile (.shp). |
required |
crs
|
str | None
|
Optional CRS to reproject the data. If None, keeps original CRS. |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame containing the shapefile data. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the shapefile does not exist. |
Exception
|
If the file cannot be read by geopandas. |
Examples:
>>> river_network = read_shapefile("example/shp/Arno_river_network.shp")
>>> reach_ids = river_network['REACH_ID']
Source code in mobidic/preprocessing/gis_reader.py
Input checks
mobidic.preprocessing.gis_reader.check_crs(crs, source)
Check the CRS of an input file.
Warns when the file has no CRS and rejects geographic CRSs, since MOBIDIC assumes coordinates, lengths and cell sizes in metres.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crs
|
Any
|
CRS of the file (rasterio/pyproj CRS, WKT, EPSG code) or None. |
required |
source
|
str | Path
|
Path of the file, used in messages. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the file has a CRS, False otherwise. |
Raises:
| Type | Description |
|---|---|
GridAlignmentError
|
If the CRS is geographic. |
Source code in mobidic/preprocessing/gis_reader.py
mobidic.preprocessing.gis_reader.check_raster_alignment(raster, reference, raster_path, reference_path)
Check that a raster has the same shape, origin, cell size and CRS as the reference (DTM).
No resampling or reprojection is performed: mismatching rasters must be fixed by the user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster
|
dict[str, Any]
|
Result of grid_to_matrix() for the raster to check. |
required |
reference
|
dict[str, Any]
|
Result of grid_to_matrix() for the reference raster (DTM). |
required |
raster_path
|
str | Path
|
Path of the raster to check, used in messages. |
required |
reference_path
|
str | Path
|
Path of the reference raster, used in messages. |
required |
Raises:
| Type | Description |
|---|---|
GridAlignmentError
|
If the raster has a geographic CRS or does not match the reference grid. |
Source code in mobidic/preprocessing/gis_reader.py
mobidic.preprocessing.gis_reader.check_vector_crs(gdf, source, reference_crs=None)
Check the CRS of a vector dataset against the reference (DTM) CRS.
Warns when the dataset has no CRS. No reprojection is performed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
Vector dataset to check. |
required |
source
|
str | Path
|
Path of the file, used in messages. |
required |
reference_crs
|
Any
|
CRS of the DTM. If None, only the geographic CRS check is performed. |
None
|
Raises:
| Type | Description |
|---|---|
GridAlignmentError
|
If the CRS is geographic or differs from the reference CRS. |
Source code in mobidic/preprocessing/gis_reader.py
Examples
Reading a Raster
from mobidic import grid_to_matrix
import numpy as np
# Read a Digital Terrain Model
dtm = grid_to_matrix("path/to/dtm.tif")
# Access raster data and metadata
print(f"Shape: {dtm['data'].shape}")
print(f"Cell size: {dtm['cellsize']} m")
print(f"Lower-left corner: ({dtm['xllcorner']}, {dtm['yllcorner']})")
print(f"CRS: {dtm['crs']}")
# Access the data array (nodata converted to NaN)
elevation = dtm['data']
mean_elevation = np.nanmean(elevation)
print(f"Mean elevation: {mean_elevation:.2f} m")
Reading a shapefile
from mobidic import read_shapefile
# Read river network shapefile
network = read_shapefile("path/to/river_network.shp")
# Access as GeoDataFrame
print(f"Number of reaches: {len(network)}")
print(f"CRS: {network.crs}")
print(network.head())
# Reproject to a different CRS
network_utm = read_shapefile(
"path/to/river_network.shp",
crs="EPSG:32632" # WGS84 / UTM zone 32N
)
Return values
Raster data
grid_to_matrix() returns a dictionary with:
data(numpy.ndarray): 2D array of raster values, nodata converted to NaN (flipped vertically to match MATLAB convention)xllcorner(float): X coordinate of lower-left corner (cell center)yllcorner(float): Y coordinate of lower-left corner (cell center)cellsize(float): Cell size in map unitscrs(rasterio.crs.CRS): Coordinate reference system
Vector data
read_shapefile() returns a geopandas.GeoDataFrame with geometry and attribute columns.
Error handling
Both functions provide detailed error messages and logging:
- File not found:
FileNotFoundErrorwith clear message - Invalid format:
RasterioIOErrororRuntimeErrorwith details - CRS issues: Warning when a file has no CRS;
GridAlignmentErrorwhen a CRS is geographic, or when a raster or shapefile does not match the DTM grid/CRS (see the input checks above) - Logging: All operations logged using loguru (DEBUG, INFO, SUCCESS, ERROR levels)