A Python package for geospatial analysis and interactive mapping in a Jupyter environment.
54
Evaluation — 54%
↓ 0.80xAgent success when using this tile
Advanced geospatial analysis tools for raster and vector data processing, including statistical analysis, geometric operations, and integration with WhiteboxTools for comprehensive analytical capabilities.
Calculate statistics for raster data within vector zones for spatial analysis and data summarization.
def zonal_stats(image, zones, stats=['count', 'mean', 'std'], **kwargs):
"""
Calculate zonal statistics for raster data within vector polygons.
Args:
image (str): Path to raster file
zones (str or gpd.GeoDataFrame): Vector zones for analysis
stats (list): Statistics to calculate ['count', 'mean', 'std', 'min', 'max', 'sum']
**kwargs: Additional options (categorical, nodata, etc.)
Returns:
gpd.GeoDataFrame: Zones with calculated statistics
"""
def add_census_data(self, dataset='states', layer_name='Census Data', **kwargs):
"""
Add and analyze US Census data.
Args:
dataset (str): Census dataset ('states', 'counties', 'tracts')
layer_name (str): Layer name for display
**kwargs: Census data options and analysis parameters
"""
def extract_values_to_points(image, points, **kwargs):
"""
Extract raster values at point locations.
Args:
image (str): Path to raster file
points (gpd.GeoDataFrame): Point locations for value extraction
**kwargs: Extraction options (band, method, etc.)
Returns:
gpd.GeoDataFrame: Points with extracted raster values
"""Comprehensive raster data processing including clipping, mosaicking, reprojection, and format conversion.
def clip_image(image, mask, output=None, **kwargs):
"""
Clip raster data using vector mask.
Args:
image (str): Path to input raster
mask (str or gpd.GeoDataFrame): Clipping geometry
output (str): Output file path
**kwargs: Clipping options (crop, nodata, etc.)
Returns:
str: Path to clipped raster if output specified
"""
def mosaic(images, output=None, **kwargs):
"""
Mosaic multiple raster files into single output.
Args:
images (list): List of raster file paths
output (str): Output mosaic file path
**kwargs: Mosaic options (method, nodata, dtype, etc.)
Returns:
str: Path to mosaic file
"""
def reproject(image, crs, output=None, **kwargs):
"""
Reproject raster to different coordinate reference system.
Args:
image (str): Input raster path
crs (str or int): Target CRS (EPSG code or proj4 string)
output (str): Output file path
**kwargs: Reprojection options (resampling, resolution, etc.)
Returns:
str: Path to reprojected raster
"""
def resample(image, resolution, output=None, **kwargs):
"""
Resample raster to different resolution.
Args:
image (str): Input raster path
resolution (float or tuple): Target resolution
output (str): Output file path
**kwargs: Resampling options (method, etc.)
Returns:
str: Path to resampled raster
"""Raster classification tools for land cover mapping and thematic analysis.
def classify(image, scheme, **kwargs):
"""
Classify raster data using specified classification scheme.
Args:
image (str): Input raster path
scheme (dict or str): Classification scheme or method
**kwargs: Classification options (classes, method, etc.)
Returns:
numpy.ndarray: Classified image array
"""
def supervised_classification(image, training_data, **kwargs):
"""
Perform supervised classification using training data.
Args:
image (str): Input raster path
training_data (gpd.GeoDataFrame): Training polygons with class labels
**kwargs: Classification options (algorithm, validation, etc.)
Returns:
numpy.ndarray: Classified image
"""
def unsupervised_classification(image, n_classes, **kwargs):
"""
Perform unsupervised classification.
Args:
image (str): Input raster path
n_classes (int): Number of classes
**kwargs: Classification options (algorithm, max_iter, etc.)
Returns:
numpy.ndarray: Classified image
"""Transform coordinates between different coordinate reference systems and perform geometric calculations.
def transform_coords(coords, src_crs, dst_crs):
"""
Transform coordinates between coordinate reference systems.
Args:
coords (list or array): Coordinates to transform [[x, y], ...]
src_crs (str or int): Source CRS
dst_crs (str or int): Destination CRS
Returns:
list: Transformed coordinates
"""
def reproject_vector(vector, target_crs, **kwargs):
"""
Reproject vector data to different CRS.
Args:
vector (str or gpd.GeoDataFrame): Input vector data
target_crs (str or int): Target coordinate reference system
**kwargs: Reprojection options
Returns:
gpd.GeoDataFrame: Reprojected vector data
"""Calculate geometric properties and perform spatial analysis on vector data.
def geometry_bounds(geometry):
"""
Calculate bounding box of geometry.
Args:
geometry: Shapely geometry object
Returns:
list: Bounding box [minx, miny, maxx, maxy]
"""
def gdf_bounds(gdf):
"""
Calculate bounding box of GeoDataFrame.
Args:
gdf (gpd.GeoDataFrame): Input GeoDataFrame
Returns:
list: Bounding box [minx, miny, maxx, maxy]
"""
def bbox_to_gdf(bbox, crs='EPSG:4326'):
"""
Convert bounding box to GeoDataFrame.
Args:
bbox (list): Bounding box [minx, miny, maxx, maxy]
crs (str): Coordinate reference system
Returns:
gpd.GeoDataFrame: Bounding box as polygon
"""
def filter_bounds(gdf, bounds):
"""
Filter GeoDataFrame by bounding box.
Args:
gdf (gpd.GeoDataFrame): Input GeoDataFrame
bounds (list): Bounding box [minx, miny, maxx, maxy]
Returns:
gpd.GeoDataFrame: Filtered GeoDataFrame
"""Analyze spatial relationships between geometries and perform overlay operations.
def spatial_join(left_gdf, right_gdf, how='inner', **kwargs):
"""
Perform spatial join between GeoDataFrames.
Args:
left_gdf (gpd.GeoDataFrame): Left GeoDataFrame
right_gdf (gpd.GeoDataFrame): Right GeoDataFrame
how (str): Join type ('inner', 'left', 'right')
**kwargs: Spatial join options (predicate, etc.)
Returns:
gpd.GeoDataFrame: Joined GeoDataFrame
"""
def overlay(gdf1, gdf2, how='intersection', **kwargs):
"""
Perform geometric overlay operation.
Args:
gdf1 (gpd.GeoDataFrame): First GeoDataFrame
gdf2 (gpd.GeoDataFrame): Second GeoDataFrame
how (str): Overlay operation ('intersection', 'union', 'difference', 'symmetric_difference')
**kwargs: Overlay options
Returns:
gpd.GeoDataFrame: Result of overlay operation
"""
def buffer_analysis(gdf, distance, **kwargs):
"""
Create buffers around geometries.
Args:
gdf (gpd.GeoDataFrame): Input geometries
distance (float): Buffer distance
**kwargs: Buffer options (resolution, cap_style, etc.)
Returns:
gpd.GeoDataFrame: Buffered geometries
"""Integration with WhiteboxTools library providing access to 500+ geoprocessing tools through GUI interface and core conversion functions.
def whiteboxgui(verbose=True, tree=False, reset=False, sandbox_path=None):
"""
Launch interactive WhiteboxTools GUI for geospatial analysis.
Args:
verbose (bool): Whether to show progress info when tools run
tree (bool): Whether to use tree mode toolbox interface
reset (bool): Whether to regenerate the tools information dictionary
sandbox_path (str): Path to sandbox folder for tool execution
Returns:
object: Interactive WhiteboxTools GUI widget
"""
class WhiteboxTools(whitebox.WhiteboxTools):
"""
WhiteboxTools class wrapper providing access to whitebox functionality.
Inherits from whitebox.WhiteboxTools with leafmap-specific enhancements.
"""
def vector_to_raster(vector, output, field="FID", assign="last", nodata=True,
cell_size=None, base=None, **kwargs):
"""
Convert vector data to raster format using WhiteboxTools.
Args:
vector (str or gpd.GeoDataFrame): Input vector data
output (str): Output raster file path
field (str): Input field name in attribute table
assign (str): Assignment operation for overlapping cells ('first', 'last', 'min', 'max', 'sum', 'number')
nodata (bool): Set background value to NoData
cell_size (float): Cell size of output raster
base (str): Input base raster file for reference
**kwargs: Additional WhiteboxTools parameters
"""
def csv_points_to_shp(in_csv, out_shp, latitude="latitude", longitude="longitude"):
"""
Convert CSV points to shapefile using WhiteboxTools.
Args:
in_csv (str): Path to input CSV file
out_shp (str): Output shapefile path
latitude (str): Column name for latitude values
longitude (str): Column name for longitude values
"""Statistical analysis tools for geospatial data including correlation, regression, and clustering.
def correlation_analysis(raster1, raster2, **kwargs):
"""
Calculate correlation between raster datasets.
Args:
raster1 (str): First raster path
raster2 (str): Second raster path
**kwargs: Analysis options (method, mask, etc.)
Returns:
dict: Correlation statistics
"""
def hotspot_analysis(gdf, values, **kwargs):
"""
Perform hotspot analysis (Getis-Ord Gi*).
Args:
gdf (gpd.GeoDataFrame): Spatial data
values (str): Column name for analysis values
**kwargs: Analysis parameters (distance_band, etc.)
Returns:
gpd.GeoDataFrame: Results with hotspot statistics
"""
def cluster_analysis(data, n_clusters, **kwargs):
"""
Perform spatial clustering analysis.
Args:
data (gpd.GeoDataFrame): Input spatial data
n_clusters (int): Number of clusters
**kwargs: Clustering parameters (algorithm, features, etc.)
Returns:
gpd.GeoDataFrame: Data with cluster assignments
"""import leafmap
# Calculate zonal statistics
results = leafmap.zonal_stats(
image='elevation.tif',
zones='watersheds.shp',
stats=['mean', 'std', 'min', 'max'],
categorical=False
)
# Display results on map
m = leafmap.Map()
m.add_gdf(results,
layer_name='Elevation Stats',
popup=['mean_elev', 'std_elev'])
mimport leafmap
# Clip raster to study area
clipped = leafmap.clip_image(
image='landsat.tif',
mask='study_area.shp',
output='clipped_landsat.tif'
)
# Reproject to UTM
reprojected = leafmap.reproject(
image=clipped,
crs='EPSG:32612', # UTM Zone 12N
output='landsat_utm.tif'
)
# Classify land cover
classified = leafmap.classify(
image=reprojected,
scheme='landcover',
output='landcover.tif'
)
# Display results
m = leafmap.Map()
m.add_raster(classified,
colormap='Set3',
layer_name='Land Cover')
mimport leafmap
import geopandas as gpd
# Load data
roads = gpd.read_file('roads.shp')
cities = gpd.read_file('cities.shp')
# Create buffers around cities
city_buffers = leafmap.buffer_analysis(
gdf=cities,
distance=5000, # 5km buffer
resolution=16
)
# Find roads within city buffers
urban_roads = leafmap.spatial_join(
left_gdf=roads,
right_gdf=city_buffers,
how='inner',
predicate='intersects'
)
# Display analysis
m = leafmap.Map()
m.add_gdf(city_buffers, layer_name='City Buffers')
m.add_gdf(urban_roads, layer_name='Urban Roads')
mimport leafmap
# Generate hillshade
leafmap.wbt_hillshade(
dem='elevation.tif',
output='hillshade.tif',
azimuth=315,
altitude=45
)
# Calculate slope
leafmap.wbt_slope(
dem='elevation.tif',
output='slope.tif',
units='degrees'
)
# Display terrain analysis
m = leafmap.Map()
m.add_raster('hillshade.tif',
colormap='gray',
layer_name='Hillshade')
m.add_raster('slope.tif',
colormap='terrain',
opacity=0.7,
layer_name='Slope')
m# Zonal statistics options
zonal_stats_options = {
'stats': ['count', 'mean', 'std', 'min', 'max', 'sum'],
'categorical': False, # Treat as categorical data
'category_map': None, # Category mapping dictionary
'nodata': -9999, # NoData value
'all_touched': True # Include partially covered pixels
}
# Classification schemes
classification_schemes = {
'equal_interval': {'n_classes': 5},
'quantiles': {'n_classes': 5},
'natural_breaks': {'n_classes': 5},
'standard_deviation': {'multiplier': 1}
}# Resampling methods
resampling_methods = [
'nearest', # Nearest neighbor
'bilinear', # Bilinear interpolation
'cubic', # Cubic convolution
'average', # Average
'mode', # Mode (most common value)
'max', # Maximum value
'min' # Minimum value
]
# Mosaic methods
mosaic_methods = [
'first', # First value encountered
'last', # Last value encountered
'min', # Minimum value
'max', # Maximum value
'mean' # Average value
]Install with Tessl CLI
npx tessl i tessl/pypi-leafmapdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10