0
# Geospatial Analysis
1
2
Advanced geospatial analysis tools for raster and vector data processing, including statistical analysis, geometric operations, and integration with WhiteboxTools for comprehensive analytical capabilities.
3
4
## Capabilities
5
6
### Zonal Statistics
7
8
Calculate statistics for raster data within vector zones for spatial analysis and data summarization.
9
10
```python { .api }
11
def zonal_stats(image, zones, stats=['count', 'mean', 'std'], **kwargs):
12
"""
13
Calculate zonal statistics for raster data within vector polygons.
14
15
Args:
16
image (str): Path to raster file
17
zones (str or gpd.GeoDataFrame): Vector zones for analysis
18
stats (list): Statistics to calculate ['count', 'mean', 'std', 'min', 'max', 'sum']
19
**kwargs: Additional options (categorical, nodata, etc.)
20
21
Returns:
22
gpd.GeoDataFrame: Zones with calculated statistics
23
"""
24
25
def add_census_data(self, dataset='states', layer_name='Census Data', **kwargs):
26
"""
27
Add and analyze US Census data.
28
29
Args:
30
dataset (str): Census dataset ('states', 'counties', 'tracts')
31
layer_name (str): Layer name for display
32
**kwargs: Census data options and analysis parameters
33
"""
34
35
def extract_values_to_points(image, points, **kwargs):
36
"""
37
Extract raster values at point locations.
38
39
Args:
40
image (str): Path to raster file
41
points (gpd.GeoDataFrame): Point locations for value extraction
42
**kwargs: Extraction options (band, method, etc.)
43
44
Returns:
45
gpd.GeoDataFrame: Points with extracted raster values
46
"""
47
```
48
49
### Raster Processing
50
51
Comprehensive raster data processing including clipping, mosaicking, reprojection, and format conversion.
52
53
```python { .api }
54
def clip_image(image, mask, output=None, **kwargs):
55
"""
56
Clip raster data using vector mask.
57
58
Args:
59
image (str): Path to input raster
60
mask (str or gpd.GeoDataFrame): Clipping geometry
61
output (str): Output file path
62
**kwargs: Clipping options (crop, nodata, etc.)
63
64
Returns:
65
str: Path to clipped raster if output specified
66
"""
67
68
def mosaic(images, output=None, **kwargs):
69
"""
70
Mosaic multiple raster files into single output.
71
72
Args:
73
images (list): List of raster file paths
74
output (str): Output mosaic file path
75
**kwargs: Mosaic options (method, nodata, dtype, etc.)
76
77
Returns:
78
str: Path to mosaic file
79
"""
80
81
def reproject(image, crs, output=None, **kwargs):
82
"""
83
Reproject raster to different coordinate reference system.
84
85
Args:
86
image (str): Input raster path
87
crs (str or int): Target CRS (EPSG code or proj4 string)
88
output (str): Output file path
89
**kwargs: Reprojection options (resampling, resolution, etc.)
90
91
Returns:
92
str: Path to reprojected raster
93
"""
94
95
def resample(image, resolution, output=None, **kwargs):
96
"""
97
Resample raster to different resolution.
98
99
Args:
100
image (str): Input raster path
101
resolution (float or tuple): Target resolution
102
output (str): Output file path
103
**kwargs: Resampling options (method, etc.)
104
105
Returns:
106
str: Path to resampled raster
107
"""
108
```
109
110
### Image Classification
111
112
Raster classification tools for land cover mapping and thematic analysis.
113
114
```python { .api }
115
def classify(image, scheme, **kwargs):
116
"""
117
Classify raster data using specified classification scheme.
118
119
Args:
120
image (str): Input raster path
121
scheme (dict or str): Classification scheme or method
122
**kwargs: Classification options (classes, method, etc.)
123
124
Returns:
125
numpy.ndarray: Classified image array
126
"""
127
128
def supervised_classification(image, training_data, **kwargs):
129
"""
130
Perform supervised classification using training data.
131
132
Args:
133
image (str): Input raster path
134
training_data (gpd.GeoDataFrame): Training polygons with class labels
135
**kwargs: Classification options (algorithm, validation, etc.)
136
137
Returns:
138
numpy.ndarray: Classified image
139
"""
140
141
def unsupervised_classification(image, n_classes, **kwargs):
142
"""
143
Perform unsupervised classification.
144
145
Args:
146
image (str): Input raster path
147
n_classes (int): Number of classes
148
**kwargs: Classification options (algorithm, max_iter, etc.)
149
150
Returns:
151
numpy.ndarray: Classified image
152
"""
153
```
154
155
### Coordinate Transformations
156
157
Transform coordinates between different coordinate reference systems and perform geometric calculations.
158
159
```python { .api }
160
def transform_coords(coords, src_crs, dst_crs):
161
"""
162
Transform coordinates between coordinate reference systems.
163
164
Args:
165
coords (list or array): Coordinates to transform [[x, y], ...]
166
src_crs (str or int): Source CRS
167
dst_crs (str or int): Destination CRS
168
169
Returns:
170
list: Transformed coordinates
171
"""
172
173
def reproject_vector(vector, target_crs, **kwargs):
174
"""
175
Reproject vector data to different CRS.
176
177
Args:
178
vector (str or gpd.GeoDataFrame): Input vector data
179
target_crs (str or int): Target coordinate reference system
180
**kwargs: Reprojection options
181
182
Returns:
183
gpd.GeoDataFrame: Reprojected vector data
184
"""
185
```
186
187
### Geometric Analysis
188
189
Calculate geometric properties and perform spatial analysis on vector data.
190
191
```python { .api }
192
def geometry_bounds(geometry):
193
"""
194
Calculate bounding box of geometry.
195
196
Args:
197
geometry: Shapely geometry object
198
199
Returns:
200
list: Bounding box [minx, miny, maxx, maxy]
201
"""
202
203
def gdf_bounds(gdf):
204
"""
205
Calculate bounding box of GeoDataFrame.
206
207
Args:
208
gdf (gpd.GeoDataFrame): Input GeoDataFrame
209
210
Returns:
211
list: Bounding box [minx, miny, maxx, maxy]
212
"""
213
214
def bbox_to_gdf(bbox, crs='EPSG:4326'):
215
"""
216
Convert bounding box to GeoDataFrame.
217
218
Args:
219
bbox (list): Bounding box [minx, miny, maxx, maxy]
220
crs (str): Coordinate reference system
221
222
Returns:
223
gpd.GeoDataFrame: Bounding box as polygon
224
"""
225
226
def filter_bounds(gdf, bounds):
227
"""
228
Filter GeoDataFrame by bounding box.
229
230
Args:
231
gdf (gpd.GeoDataFrame): Input GeoDataFrame
232
bounds (list): Bounding box [minx, miny, maxx, maxy]
233
234
Returns:
235
gpd.GeoDataFrame: Filtered GeoDataFrame
236
"""
237
```
238
239
### Spatial Relationships
240
241
Analyze spatial relationships between geometries and perform overlay operations.
242
243
```python { .api }
244
def spatial_join(left_gdf, right_gdf, how='inner', **kwargs):
245
"""
246
Perform spatial join between GeoDataFrames.
247
248
Args:
249
left_gdf (gpd.GeoDataFrame): Left GeoDataFrame
250
right_gdf (gpd.GeoDataFrame): Right GeoDataFrame
251
how (str): Join type ('inner', 'left', 'right')
252
**kwargs: Spatial join options (predicate, etc.)
253
254
Returns:
255
gpd.GeoDataFrame: Joined GeoDataFrame
256
"""
257
258
def overlay(gdf1, gdf2, how='intersection', **kwargs):
259
"""
260
Perform geometric overlay operation.
261
262
Args:
263
gdf1 (gpd.GeoDataFrame): First GeoDataFrame
264
gdf2 (gpd.GeoDataFrame): Second GeoDataFrame
265
how (str): Overlay operation ('intersection', 'union', 'difference', 'symmetric_difference')
266
**kwargs: Overlay options
267
268
Returns:
269
gpd.GeoDataFrame: Result of overlay operation
270
"""
271
272
def buffer_analysis(gdf, distance, **kwargs):
273
"""
274
Create buffers around geometries.
275
276
Args:
277
gdf (gpd.GeoDataFrame): Input geometries
278
distance (float): Buffer distance
279
**kwargs: Buffer options (resolution, cap_style, etc.)
280
281
Returns:
282
gpd.GeoDataFrame: Buffered geometries
283
"""
284
```
285
286
### WhiteboxTools Integration
287
288
Integration with WhiteboxTools library providing access to 500+ geoprocessing tools through GUI interface and core conversion functions.
289
290
```python { .api }
291
def whiteboxgui(verbose=True, tree=False, reset=False, sandbox_path=None):
292
"""
293
Launch interactive WhiteboxTools GUI for geospatial analysis.
294
295
Args:
296
verbose (bool): Whether to show progress info when tools run
297
tree (bool): Whether to use tree mode toolbox interface
298
reset (bool): Whether to regenerate the tools information dictionary
299
sandbox_path (str): Path to sandbox folder for tool execution
300
301
Returns:
302
object: Interactive WhiteboxTools GUI widget
303
"""
304
305
class WhiteboxTools(whitebox.WhiteboxTools):
306
"""
307
WhiteboxTools class wrapper providing access to whitebox functionality.
308
Inherits from whitebox.WhiteboxTools with leafmap-specific enhancements.
309
"""
310
311
def vector_to_raster(vector, output, field="FID", assign="last", nodata=True,
312
cell_size=None, base=None, **kwargs):
313
"""
314
Convert vector data to raster format using WhiteboxTools.
315
316
Args:
317
vector (str or gpd.GeoDataFrame): Input vector data
318
output (str): Output raster file path
319
field (str): Input field name in attribute table
320
assign (str): Assignment operation for overlapping cells ('first', 'last', 'min', 'max', 'sum', 'number')
321
nodata (bool): Set background value to NoData
322
cell_size (float): Cell size of output raster
323
base (str): Input base raster file for reference
324
**kwargs: Additional WhiteboxTools parameters
325
"""
326
327
def csv_points_to_shp(in_csv, out_shp, latitude="latitude", longitude="longitude"):
328
"""
329
Convert CSV points to shapefile using WhiteboxTools.
330
331
Args:
332
in_csv (str): Path to input CSV file
333
out_shp (str): Output shapefile path
334
latitude (str): Column name for latitude values
335
longitude (str): Column name for longitude values
336
"""
337
```
338
339
### Statistical Analysis
340
341
Statistical analysis tools for geospatial data including correlation, regression, and clustering.
342
343
```python { .api }
344
def correlation_analysis(raster1, raster2, **kwargs):
345
"""
346
Calculate correlation between raster datasets.
347
348
Args:
349
raster1 (str): First raster path
350
raster2 (str): Second raster path
351
**kwargs: Analysis options (method, mask, etc.)
352
353
Returns:
354
dict: Correlation statistics
355
"""
356
357
def hotspot_analysis(gdf, values, **kwargs):
358
"""
359
Perform hotspot analysis (Getis-Ord Gi*).
360
361
Args:
362
gdf (gpd.GeoDataFrame): Spatial data
363
values (str): Column name for analysis values
364
**kwargs: Analysis parameters (distance_band, etc.)
365
366
Returns:
367
gpd.GeoDataFrame: Results with hotspot statistics
368
"""
369
370
def cluster_analysis(data, n_clusters, **kwargs):
371
"""
372
Perform spatial clustering analysis.
373
374
Args:
375
data (gpd.GeoDataFrame): Input spatial data
376
n_clusters (int): Number of clusters
377
**kwargs: Clustering parameters (algorithm, features, etc.)
378
379
Returns:
380
gpd.GeoDataFrame: Data with cluster assignments
381
"""
382
```
383
384
## Usage Examples
385
386
### Zonal Statistics Analysis
387
388
```python
389
import leafmap
390
391
# Calculate zonal statistics
392
results = leafmap.zonal_stats(
393
image='elevation.tif',
394
zones='watersheds.shp',
395
stats=['mean', 'std', 'min', 'max'],
396
categorical=False
397
)
398
399
# Display results on map
400
m = leafmap.Map()
401
m.add_gdf(results,
402
layer_name='Elevation Stats',
403
popup=['mean_elev', 'std_elev'])
404
m
405
```
406
407
### Raster Processing Workflow
408
409
```python
410
import leafmap
411
412
# Clip raster to study area
413
clipped = leafmap.clip_image(
414
image='landsat.tif',
415
mask='study_area.shp',
416
output='clipped_landsat.tif'
417
)
418
419
# Reproject to UTM
420
reprojected = leafmap.reproject(
421
image=clipped,
422
crs='EPSG:32612', # UTM Zone 12N
423
output='landsat_utm.tif'
424
)
425
426
# Classify land cover
427
classified = leafmap.classify(
428
image=reprojected,
429
scheme='landcover',
430
output='landcover.tif'
431
)
432
433
# Display results
434
m = leafmap.Map()
435
m.add_raster(classified,
436
colormap='Set3',
437
layer_name='Land Cover')
438
m
439
```
440
441
### Spatial Analysis Workflow
442
443
```python
444
import leafmap
445
import geopandas as gpd
446
447
# Load data
448
roads = gpd.read_file('roads.shp')
449
cities = gpd.read_file('cities.shp')
450
451
# Create buffers around cities
452
city_buffers = leafmap.buffer_analysis(
453
gdf=cities,
454
distance=5000, # 5km buffer
455
resolution=16
456
)
457
458
# Find roads within city buffers
459
urban_roads = leafmap.spatial_join(
460
left_gdf=roads,
461
right_gdf=city_buffers,
462
how='inner',
463
predicate='intersects'
464
)
465
466
# Display analysis
467
m = leafmap.Map()
468
m.add_gdf(city_buffers, layer_name='City Buffers')
469
m.add_gdf(urban_roads, layer_name='Urban Roads')
470
m
471
```
472
473
### WhiteboxTools Analysis
474
475
```python
476
import leafmap
477
478
# Generate hillshade
479
leafmap.wbt_hillshade(
480
dem='elevation.tif',
481
output='hillshade.tif',
482
azimuth=315,
483
altitude=45
484
)
485
486
# Calculate slope
487
leafmap.wbt_slope(
488
dem='elevation.tif',
489
output='slope.tif',
490
units='degrees'
491
)
492
493
# Display terrain analysis
494
m = leafmap.Map()
495
m.add_raster('hillshade.tif',
496
colormap='gray',
497
layer_name='Hillshade')
498
m.add_raster('slope.tif',
499
colormap='terrain',
500
opacity=0.7,
501
layer_name='Slope')
502
m
503
```
504
505
## Analysis Parameters
506
507
### Statistical Options
508
509
```python
510
# Zonal statistics options
511
zonal_stats_options = {
512
'stats': ['count', 'mean', 'std', 'min', 'max', 'sum'],
513
'categorical': False, # Treat as categorical data
514
'category_map': None, # Category mapping dictionary
515
'nodata': -9999, # NoData value
516
'all_touched': True # Include partially covered pixels
517
}
518
519
# Classification schemes
520
classification_schemes = {
521
'equal_interval': {'n_classes': 5},
522
'quantiles': {'n_classes': 5},
523
'natural_breaks': {'n_classes': 5},
524
'standard_deviation': {'multiplier': 1}
525
}
526
```
527
528
### Processing Options
529
530
```python
531
# Resampling methods
532
resampling_methods = [
533
'nearest', # Nearest neighbor
534
'bilinear', # Bilinear interpolation
535
'cubic', # Cubic convolution
536
'average', # Average
537
'mode', # Mode (most common value)
538
'max', # Maximum value
539
'min' # Minimum value
540
]
541
542
# Mosaic methods
543
mosaic_methods = [
544
'first', # First value encountered
545
'last', # Last value encountered
546
'min', # Minimum value
547
'max', # Maximum value
548
'mean' # Average value
549
]
550
```