0
# Configuration and Utilities
1
2
Global configuration options, version information, exception handling, and utility functions for CRS conversion and coordinate management. These components provide configuration control and diagnostic capabilities for rioxarray.
3
4
## Capabilities
5
6
### Global Configuration Options
7
8
Control rioxarray behavior through global configuration settings that affect file I/O, metadata handling, and spatial operations.
9
10
```python { .api }
11
class set_options:
12
"""
13
Set global rioxarray options as context manager or permanent setting.
14
15
Parameters:
16
- export_grid_mapping: bool (default=True) - Export full CF grid mapping attributes
17
- skip_missing_spatial_dims: bool (default=False) - Skip operations on vars without spatial dims
18
19
Usage as context manager:
20
with rioxarray.set_options(export_grid_mapping=False):
21
# operations with modified settings
22
23
Usage for global settings:
24
rioxarray.set_options(export_grid_mapping=False)
25
"""
26
27
```
28
29
#### Usage Examples
30
31
```python
32
import rioxarray
33
34
# Set options globally
35
rioxarray.set_options(export_grid_mapping=False)
36
rioxarray.set_options(skip_missing_spatial_dims=True)
37
38
# Use as context manager (temporary setting)
39
with rioxarray.set_options(export_grid_mapping=False):
40
# Operations here won't export full grid mapping
41
da = rioxarray.open_rasterio('file.tif')
42
da.rio.write_crs(inplace=True) # Only writes crs_wkt and spatial_ref
43
44
# Settings revert after context manager
45
46
# Configure for performance (skip CF grid mapping for speed)
47
rioxarray.set_options(export_grid_mapping=False)
48
49
# Configure for datasets with missing spatial dimensions
50
rioxarray.set_options(skip_missing_spatial_dims=True)
51
```
52
53
### Version Information
54
55
Display comprehensive version and system information for debugging and environment verification.
56
57
```python { .api }
58
def show_versions() -> None:
59
"""
60
Print useful debugging information including rioxarray version,
61
dependencies, and system information.
62
63
Output includes:
64
- rioxarray version and main dependencies (rasterio, xarray, GDAL, GEOS, PROJ)
65
- Other Python dependencies (scipy, pyproj)
66
- System information (Python version, platform, executable path)
67
- GDAL and PROJ data paths
68
"""
69
```
70
71
#### Usage Examples
72
73
```python
74
import rioxarray
75
76
# Display comprehensive version information
77
rioxarray.show_versions()
78
79
# Example output:
80
# rioxarray (0.19.0) deps:
81
# rasterio: 1.3.9
82
# xarray: 2024.7.0
83
# GDAL: 3.8.4
84
# GEOS: 3.12.1
85
# PROJ: 9.4.0
86
# PROJ DATA: /opt/conda/share/proj
87
# GDAL DATA: /opt/conda/share/gdal
88
#
89
# Other python deps:
90
# scipy: 1.11.4
91
# pyproj: 3.6.1
92
#
93
# System:
94
# python: 3.11.7
95
#executable: /opt/conda/bin/python
96
# machine: Linux-5.15.0-91-generic-x86_64
97
98
# Use in scripts for debugging
99
try:
100
da = rioxarray.open_rasterio('problem_file.tif')
101
except Exception as e:
102
print("Error occurred. Environment info:")
103
rioxarray.show_versions()
104
raise
105
```
106
107
### Exception Hierarchy
108
109
Comprehensive exception classes for handling different types of errors in geospatial operations.
110
111
```python { .api }
112
# Base exception
113
class RioXarrayError(RuntimeError):
114
"""Base exception for errors in the rioxarray extension."""
115
116
# Data-related exceptions
117
class NoDataInBounds(RioXarrayError):
118
"""Raised when there is no data within the bounds for clipping a raster."""
119
120
class SingleVariableDataset(RioXarrayError):
121
"""Raised when operations expect multiple variables but dataset has only one."""
122
123
# Dimension-related exceptions
124
class DimensionError(RioXarrayError):
125
"""Base class for dimension-related errors."""
126
127
class MissingSpatialDimensionError(DimensionError):
128
"""Raised when required spatial dimensions cannot be found."""
129
130
class TooManyDimensions(DimensionError):
131
"""Raised when there are more dimensions than supported by the method."""
132
133
class InvalidDimensionOrder(DimensionError):
134
"""Raised when dimensions are not in the expected order."""
135
136
class OneDimensionalRaster(DimensionError):
137
"""Raised when a raster has only one spatial dimension."""
138
139
class DimensionMissingCoordinateError(RioXarrayError):
140
"""Raised when a dimension does not have supporting coordinates."""
141
142
# CRS-related exceptions
143
class MissingCRS(RioXarrayError):
144
"""Raised when CRS is required but missing from dataset."""
145
```
146
147
#### Usage Examples
148
149
```python
150
import rioxarray
151
from rioxarray.exceptions import NoDataInBounds, MissingCRS, MissingSpatialDimensionError
152
153
try:
154
da = rioxarray.open_rasterio('file.tif')
155
156
# This might raise NoDataInBounds
157
geometry = {...} # Geometry outside raster bounds
158
clipped = da.rio.clip([geometry])
159
160
except NoDataInBounds as e:
161
print(f"No data in clipping area: {e}")
162
163
except MissingCRS as e:
164
print(f"CRS required but not found: {e}")
165
166
except MissingSpatialDimensionError as e:
167
print(f"Missing spatial dimensions: {e}")
168
169
except rioxarray.RioXarrayError as e:
170
print(f"General rioxarray error: {e}")
171
172
# Handle specific dimension errors
173
try:
174
# Operation requiring 2D data
175
da_1d = da.isel(x=0) # Creates 1D array
176
reprojected = da_1d.rio.reproject('EPSG:4326')
177
178
except OneDimensionalRaster as e:
179
print(f"Cannot reproject 1D raster: {e}")
180
181
# CRS validation
182
try:
183
da_no_crs = rioxarray.open_rasterio('no_crs_file.tif')
184
bounds = da_no_crs.rio.transform_bounds('EPSG:4326')
185
186
except MissingCRS as e:
187
print(f"Set CRS first: {e}")
188
da_no_crs.rio.set_crs('EPSG:4326') # Fix the issue
189
```
190
191
### CRS Utility Functions
192
193
Helper functions for working with coordinate reference systems and handling various CRS input formats.
194
195
```python { .api }
196
def crs_from_user_input(crs_input: Any) -> rasterio.crs.CRS:
197
"""
198
Convert various CRS input formats to a standardized rasterio.crs.CRS object.
199
200
Handles transitions between GDAL versions and normalizes different CRS representations.
201
202
Parameters:
203
- crs_input: CRS in various formats (EPSG code, PROJ string, WKT, dict, CRS object)
204
205
Returns:
206
rasterio.crs.CRS: Standardized CRS object
207
208
Raises:
209
ValueError: If CRS input cannot be parsed
210
"""
211
```
212
213
#### Usage Examples
214
215
```python
216
from rioxarray.crs import crs_from_user_input
217
218
# Convert various CRS input formats
219
crs1 = crs_from_user_input('EPSG:4326') # EPSG string
220
crs2 = crs_from_user_input(4326) # EPSG integer
221
crs3 = crs_from_user_input('+proj=longlat +datum=WGS84') # PROJ string
222
crs4 = crs_from_user_input({'init': 'epsg:4326'}) # Dictionary
223
crs5 = crs_from_user_input(crs1) # Already CRS object
224
225
# All produce equivalent results
226
print(crs1 == crs2 == crs3 == crs4 == crs5) # True
227
228
# Use in custom functions
229
def normalize_crs(input_crs):
230
"""Helper to ensure consistent CRS handling"""
231
return crs_from_user_input(input_crs)
232
233
# Handle invalid CRS
234
try:
235
invalid_crs = crs_from_user_input('INVALID:9999')
236
except ValueError as e:
237
print(f"Invalid CRS: {e}")
238
```
239
240
## Configuration Patterns
241
242
### Development vs Production Settings
243
244
```python
245
import rioxarray
246
247
# Development settings (full debugging info)
248
rioxarray.set_options(
249
export_grid_mapping=True, # Full CF compliance
250
skip_missing_spatial_dims=False # Strict validation
251
)
252
253
# Production settings (optimized for performance)
254
rioxarray.set_options(
255
export_grid_mapping=False, # Skip expensive CF mapping
256
skip_missing_spatial_dims=True # Skip vars without spatial dims
257
)
258
259
# Context-specific settings
260
def process_for_analysis():
261
with rioxarray.set_options(export_grid_mapping=True):
262
# Full metadata for analysis
263
return rioxarray.open_rasterio('analysis_data.tif')
264
265
def process_for_display():
266
with rioxarray.set_options(export_grid_mapping=False):
267
# Fast loading for visualization
268
return rioxarray.open_rasterio('display_data.tif')
269
```
270
271
### Error Handling Strategies
272
273
```python
274
import rioxarray
275
from rioxarray.exceptions import *
276
277
def robust_geospatial_operation(file_path, geometry):
278
"""Example of comprehensive error handling"""
279
try:
280
# Load data
281
da = rioxarray.open_rasterio(file_path)
282
283
# Validate CRS
284
if da.rio.crs is None:
285
raise MissingCRS("Dataset has no CRS defined")
286
287
# Perform clipping with error handling
288
try:
289
clipped = da.rio.clip([geometry])
290
except NoDataInBounds:
291
print("No data in geometry bounds, returning None")
292
return None
293
294
return clipped
295
296
except MissingSpatialDimensionError as e:
297
print(f"Spatial dimension issue: {e}")
298
# Try to fix dimension issues
299
if hasattr(da, 'squeeze'):
300
da = da.squeeze() # Remove single dimensions
301
return da.rio.clip([geometry])
302
raise
303
304
except TooManyDimensions as e:
305
print(f"Too many dimensions: {e}")
306
# Select first band if multi-band
307
if len(da.dims) > 2:
308
da = da.isel(band=0)
309
return da.rio.clip([geometry])
310
raise
311
312
except RioXarrayError as e:
313
print(f"Rioxarray error: {e}")
314
rioxarray.show_versions() # Debug info
315
raise
316
```
317
318
### Environment Configuration
319
320
```python
321
import rioxarray
322
import os
323
324
# Environment-based configuration
325
def configure_rioxarray():
326
"""Configure rioxarray based on environment"""
327
328
# Check if in CI/testing environment
329
if os.getenv('CI') or os.getenv('PYTEST_CURRENT_TEST'):
330
rioxarray.set_options(
331
export_grid_mapping=False, # Faster tests
332
skip_missing_spatial_dims=True
333
)
334
335
# Check if debugging
336
elif os.getenv('DEBUG'):
337
rioxarray.set_options(
338
export_grid_mapping=True, # Full metadata
339
skip_missing_spatial_dims=False # Strict validation
340
)
341
342
# Production environment
343
else:
344
rioxarray.set_options(
345
export_grid_mapping=True, # CF compliance
346
skip_missing_spatial_dims=True # Performance
347
)
348
349
# Initialize configuration
350
configure_rioxarray()
351
352
# Display environment info for debugging
353
if os.getenv('DEBUG'):
354
rioxarray.show_versions()
355
```
356
357
## Best Practices
358
359
### Configuration Management
360
- Use context managers for temporary setting changes
361
- Set global options at application startup
362
- Document configuration choices and their impact on performance/compliance
363
364
### Error Handling
365
- Catch specific exceptions rather than generic Exception
366
- Use NoDataInBounds to handle empty clip results gracefully
367
- Check for MissingCRS before CRS-dependent operations
368
- Validate spatial dimensions before performing spatial operations
369
370
### Debugging and Diagnostics
371
- Call `show_versions()` when reporting issues
372
- Include environment information in error reports
373
- Use configuration options to enable/disable expensive operations during development