CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-leafmap

A Python package for geospatial analysis and interactive mapping in a Jupyter environment.

54

0.80x

Evaluation54%

0.80x

Agent success when using this tile

Overview
Eval results
Files

file-io.mddocs/

File I/O and Data Processing

Comprehensive file input/output capabilities supporting various geospatial formats, coordinate transformations, data conversion utilities, and download functionality for seamless data workflows.

Capabilities

File Download and Web Access

Download files from URLs with progress tracking, authentication support, and error handling for reliable data acquisition.

def download_file(url, filename=None, **kwargs):
    """
    Download file from URL.
    
    Args:
        url (str): URL to download from
        filename (str): Local filename for downloaded file
        **kwargs: Download options (headers, timeout, verify, etc.)
        
    Returns:
        str: Path to downloaded file
    """

def download_from_url(url, out_file, **kwargs):
    """
    Advanced download with progress tracking.
    
    Args:
        url (str): Source URL
        out_file (str): Output file path  
        **kwargs: Advanced options (chunk_size, progress, resume, etc.)
        
    Returns:
        str: Path to downloaded file
    """

def download_folder(url, out_dir, **kwargs):
    """
    Download entire folder from URL.
    
    Args:
        url (str): Folder URL
        out_dir (str): Output directory
        **kwargs: Download options (recursive, filters, etc.)
        
    Returns:
        list: List of downloaded file paths
    """

Raster Data I/O

Read, write, and process raster data in various formats with comprehensive metadata handling and format conversion.

def read_raster(filename, **kwargs):
    """
    Read raster file into memory.
    
    Args:
        filename (str): Path to raster file
        **kwargs: Read options (bands, window, masked, etc.)
        
    Returns:
        tuple: (array, metadata) - raster data and metadata
    """

def write_raster(array, filename, **kwargs):
    """
    Write raster array to file.
    
    Args:
        array (numpy.ndarray): Raster data array
        filename (str): Output file path
        **kwargs: Write options (crs, transform, compress, etc.)
        
    Returns:
        str: Path to written raster file
    """

def raster_info(filename):
    """
    Get raster file information.
    
    Args:
        filename (str): Path to raster file
        
    Returns:
        dict: Raster metadata (bands, CRS, bounds, etc.)
    """

def read_netcdf(filename, variables=None, **kwargs):
    """
    Read NetCDF file.
    
    Args:
        filename (str): Path to NetCDF file
        variables (list): Variables to read
        **kwargs: NetCDF read options (time, bbox, etc.)
        
    Returns:
        xarray.Dataset: NetCDF data as xarray Dataset
    """

Vector Data I/O

Read, write, and convert vector data supporting multiple formats with attribute handling and spatial indexing.

def read_vector(filename, **kwargs):
    """
    Read vector file into GeoDataFrame.
    
    Args:
        filename (str): Path to vector file
        **kwargs: Read options (bbox, rows, columns, etc.)
        
    Returns:
        gpd.GeoDataFrame: Vector data as GeoDataFrame
    """

def write_vector(gdf, filename, **kwargs):
    """
    Write GeoDataFrame to vector file.
    
    Args:
        gdf (gpd.GeoDataFrame): GeoDataFrame to write
        filename (str): Output file path
        **kwargs: Write options (driver, crs, etc.)
        
    Returns:
        str: Path to written vector file
    """

def vector_info(filename):
    """
    Get vector file information.
    
    Args:
        filename (str): Path to vector file
        
    Returns:
        dict: Vector metadata (geometry_type, CRS, bounds, feature_count, etc.)
    """

def read_lidar(filename, **kwargs):
    """
    Read LiDAR data file.
    
    Args:
        filename (str): Path to LiDAR file (.las, .laz)
        **kwargs: LiDAR read options (classification, returns, etc.)
        
    Returns:
        dict: LiDAR points and metadata
    """

Data Format Conversion

Convert between different geospatial data formats with comprehensive format support and customizable conversion options.

def csv_to_geojson(filename, lat='latitude', lon='longitude', **kwargs):
    """
    Convert CSV file to GeoJSON.
    
    Args:
        filename (str): Path to CSV file
        lat (str): Latitude column name
        lon (str): Longitude column name
        **kwargs: Conversion options (crs, properties, etc.)
        
    Returns:
        str: Path to GeoJSON file
    """

def csv_to_gdf(filename, lat='latitude', lon='longitude', **kwargs):
    """
    Convert CSV to GeoDataFrame.
    
    Args:
        filename (str): Path to CSV file
        lat (str): Latitude column name
        lon (str): Longitude column name
        **kwargs: Conversion options (crs, etc.)
        
    Returns:
        gpd.GeoDataFrame: CSV data as GeoDataFrame
    """

def csv_to_shp(filename, output, lat='latitude', lon='longitude', **kwargs):
    """
    Convert CSV to shapefile.
    
    Args:
        filename (str): Path to CSV file
        output (str): Output shapefile path
        lat (str): Latitude column name
        lon (str): Longitude column name
        **kwargs: Conversion options (crs, etc.)
        
    Returns:
        str: Path to created shapefile
    """

def geojson_to_gdf(filename, **kwargs):
    """
    Convert GeoJSON to GeoDataFrame.
    
    Args:
        filename (str): Path to GeoJSON file
        **kwargs: Conversion options
        
    Returns:
        gpd.GeoDataFrame: GeoJSON as GeoDataFrame
    """

def shp_to_geojson(filename, **kwargs):
    """
    Convert shapefile to GeoJSON.
    
    Args:
        filename (str): Path to shapefile
        **kwargs: Conversion options (crs, precision, etc.)
        
    Returns:
        str: Path to GeoJSON file
    """

def vector_to_geojson(filename, **kwargs):
    """
    Convert any vector format to GeoJSON.
    
    Args:
        filename (str): Path to vector file
        **kwargs: Conversion options
        
    Returns:
        str: Path to GeoJSON file
    """

Image Processing and Conversion

Process and convert images with geospatial metadata handling and format optimization.

def image_to_cog(filename, output=None, **kwargs):
    """
    Convert image to Cloud Optimized GeoTIFF.
    
    Args:
        filename (str): Input image path
        output (str): Output COG path
        **kwargs: COG creation options (compress, overview, blocksize, etc.)
        
    Returns:
        str: Path to COG file
    """

def numpy_to_cog(array, filename, **kwargs):
    """
    Convert NumPy array to COG.
    
    Args:
        array (numpy.ndarray): Input array
        filename (str): Output COG path
        **kwargs: COG options (crs, transform, nodata, etc.)
        
    Returns:
        str: Path to COG file
    """

def array_to_image(array, filename, **kwargs):
    """
    Convert NumPy array to image file.
    
    Args:
        array (numpy.ndarray): Input array
        filename (str): Output image path
        **kwargs: Image options (format, quality, etc.)
        
    Returns:
        str: Path to image file
    """

def images_to_gif(images, output, **kwargs):
    """
    Convert image sequence to animated GIF.
    
    Args:
        images (list): List of image file paths
        output (str): Output GIF path
        **kwargs: GIF options (duration, loop, optimize, etc.)
        
    Returns:
        str: Path to GIF file
    """

Archive and Compression

Handle compressed archives and files with support for various compression formats.

def extract_archive(filename, output_dir=None, **kwargs):
    """
    Extract compressed archive.
    
    Args:
        filename (str): Path to archive file (.zip, .tar.gz, etc.)
        output_dir (str): Extraction directory
        **kwargs: Extraction options (members, password, etc.)
        
    Returns:
        list: List of extracted file paths
    """

def create_archive(files, output, **kwargs):
    """
    Create compressed archive from files.
    
    Args:
        files (list): List of file paths to archive
        output (str): Output archive path
        **kwargs: Archive options (compression, password, etc.)
        
    Returns:
        str: Path to created archive
    """

def compress_file(filename, **kwargs):
    """
    Compress single file.
    
    Args:
        filename (str): File to compress
        **kwargs: Compression options (level, format, etc.)
        
    Returns:
        str: Path to compressed file
    """

Metadata and Information

Extract and manage metadata from geospatial files with comprehensive format support.

def get_metadata(filename):
    """
    Get comprehensive metadata from geospatial file.
    
    Args:
        filename (str): Path to geospatial file
        
    Returns:
        dict: Complete metadata including CRS, bounds, format info, etc.
    """

def get_crs(filename):
    """
    Get coordinate reference system from file.
    
    Args:
        filename (str): Path to geospatial file
        
    Returns:
        pyproj.CRS: Coordinate reference system
    """

def get_bounds(filename):
    """
    Get spatial bounds from file.
    
    Args:
        filename (str): Path to geospatial file
        
    Returns:
        list: Bounding box [minx, miny, maxx, maxy]
    """

def file_size(filename):
    """
    Get file size in human-readable format.
    
    Args:
        filename (str): Path to file
        
    Returns:
        str: File size (e.g., '15.3 MB')
    """

Usage Examples

Basic File I/O Operations

import leafmap

# Download a file
leafmap.download_file(
    'https://example.com/data.tif',
    'local_data.tif'
)

# Read raster data
array, metadata = leafmap.read_raster('local_data.tif')

print(f"Raster shape: {array.shape}")
print(f"CRS: {metadata['crs']}")

# Read vector data
gdf = leafmap.read_vector('vector_data.shp')
print(f"Features: {len(gdf)}")

Data Format Conversion Workflow

import leafmap

# Convert CSV with coordinates to GeoJSON
leafmap.csv_to_geojson(
    'points.csv',
    lat='lat_column',
    lon='lon_column',
    output='points.geojson'
)

# Convert shapefile to GeoJSON
leafmap.shp_to_geojson(
    'boundaries.shp',
    output='boundaries.geojson'
)

# Convert to GeoDataFrame for analysis
gdf = leafmap.geojson_to_gdf('points.geojson')

# Process and save back
gdf_processed = gdf[gdf['value'] > 100]  # Filter
leafmap.write_vector(gdf_processed, 'filtered_points.gpkg')

Image Processing Pipeline

import leafmap
import numpy as np

# Read raster
array, metadata = leafmap.read_raster('input.tif')

# Process array (example: threshold)
processed = np.where(array > 0.5, 1, 0)

# Convert to COG
leafmap.numpy_to_cog(
    processed,
    'processed.tif',
    crs=metadata['crs'],
    transform=metadata['transform'],
    compress='lzw'
)

# Create visualization
leafmap.array_to_image(
    processed,
    'visualization.png'
)

Batch File Processing

import leafmap
import glob

# Find all shapefiles
shapefiles = glob.glob('data/*.shp')

# Convert all to GeoJSON
geojson_files = []
for shp in shapefiles:
    geojson = leafmap.shp_to_geojson(shp)
    geojson_files.append(geojson)

print(f"Converted {len(geojson_files)} files")

# Combine all into single GeoDataFrame
import geopandas as gpd
combined = gpd.GeoDataFrame()

for geojson in geojson_files:
    gdf = leafmap.geojson_to_gdf(geojson)
    combined = gpd.concat([combined, gdf])

# Save combined data
leafmap.write_vector(combined, 'combined_data.gpkg')

NetCDF Data Processing

import leafmap

# Read NetCDF file
dataset = leafmap.read_netcdf(
    'climate_data.nc',
    variables=['temperature', 'precipitation']
)

print(f"Variables: {list(dataset.variables)}")
print(f"Time range: {dataset.time.min().values} to {dataset.time.max().values}")

# Extract single time slice
temp_slice = dataset['temperature'].isel(time=0)

# Convert to raster
leafmap.numpy_to_cog(
    temp_slice.values,
    'temperature.tif',
    crs='EPSG:4326',
    bounds=[-180, -90, 180, 90]
)

LiDAR Data Processing

import leafmap

# Read LiDAR file
lidar_data = leafmap.read_lidar(
    'pointcloud.las',
    classification=[2, 3, 4, 5]  # Ground, low/medium/high vegetation
)

print(f"Points: {len(lidar_data['points'])}")
print(f"Classifications: {set(lidar_data['classification'])}")

# Create DEM from ground points
ground_points = lidar_data['points'][lidar_data['classification'] == 2]

# Process to raster (would need additional gridding)
# This is a simplified example
dem_array = process_points_to_grid(ground_points)  # Custom function

leafmap.numpy_to_cog(
    dem_array,
    'dem.tif',
    crs='EPSG:32612'  # UTM zone
)

File Format Support

Raster Formats

  • GeoTIFF (.tif, .tiff): Standard geospatial raster format
  • COG: Cloud Optimized GeoTIFF for web access
  • NetCDF (.nc, .nc4): Climate and oceanographic data
  • HDF5 (.h5, .hdf5): Hierarchical scientific data
  • JPEG2000 (.jp2): Compressed imagery
  • PNG/JPEG (.png, .jpg): Standard image formats
  • ENVI (.img): Remote sensing format

Vector Formats

  • Shapefile (.shp): Standard vector format
  • GeoJSON (.geojson, .json): Web-friendly vector format
  • GeoPackage (.gpkg): Modern SQLite-based format
  • KML/KMZ (.kml, .kmz): Google Earth format
  • GML (.gml): Geography Markup Language
  • PostGIS: PostgreSQL spatial extension
  • FileGDB (.gdb): Esri geodatabase

Specialized Formats

  • LAS/LAZ (.las, .laz): LiDAR point cloud data
  • CSV (.csv): Comma-separated values with coordinates
  • Excel (.xlsx, .xls): Spreadsheet formats
  • Parquet (.parquet): Columnar data format

Compression and Archives

  • ZIP (.zip): Standard compression
  • TAR (.tar, .tar.gz, .tgz): Unix archive format
  • 7Z (.7z): High compression ratio
  • RAR (.rar): WinRAR format

Configuration Options

Download Options

download_options = {
    'headers': {'User-Agent': 'leafmap'},  # Custom headers
    'timeout': 300,                        # Timeout in seconds
    'verify': True,                        # SSL verification
    'chunk_size': 8192,                    # Download chunk size
    'resume': True,                        # Resume interrupted downloads
    'progress': True                       # Show progress bar
}

Raster I/O Options

raster_options = {
    'bands': [1, 2, 3],                   # Specific bands to read
    'window': ((0, 512), (0, 512)),       # Spatial window
    'masked': True,                       # Return masked array
    'dtype': 'float32',                   # Data type
    'compress': 'lzw',                    # Compression method
    'tiled': True,                        # Tiled output
    'blockxsize': 512,                    # Tile width
    'blockysize': 512                     # Tile height
}

Vector I/O Options

vector_options = {
    'bbox': [-180, -90, 180, 90],         # Bounding box filter
    'rows': slice(0, 1000),               # Row slice
    'columns': ['name', 'value'],         # Column selection
    'driver': 'GeoJSON',                  # Output driver
    'precision': 6,                       # Coordinate precision
    'drop_z': True                        # Drop Z coordinates
}

Install with Tessl CLI

npx tessl i tessl/pypi-leafmap

docs

basemaps.md

cloud-data.md

data-visualization.md

file-io.md

geospatial-analysis.md

index.md

interactive-maps.md

osm-integration.md

statistical-plotting.md

tile.json