CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cartopy

A Python package designed to make drawing maps for data analysis and visualisation easy

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

data-io.mddocs/

Data Input/Output

Access to various geospatial data sources including web tile services, elevation data, and shapefile readers. Provides caching, automatic data downloading, and support for multiple data formats.

Capabilities

Base IO Classes

Core classes for handling data downloads and raster sources.

class Downloader:
    """Resource downloader with caching and automatic acquisition."""
    def __init__(self, url_template, target_path_template, 
                 pre_downloaded_path_template=''): ...
    def url(self, format_dict): ...
    def target_path(self, format_dict): ...
    def pre_downloaded_path(self, format_dict): ...
    def path(self, format_dict): ...
    def acquire_resource(self, target_path, format_dict): ...
    @staticmethod
    def from_config(specification, config_dict=None): ...

class LocatedImage:
    """Image with associated spatial extent."""
    image: Any
    extent: Tuple[float, float, float, float]

class RasterSource:
    """Abstract interface for raster data sources."""
    def validate_projection(self, projection): ...
    def fetch_raster(self, projection, extent, target_resolution): ...

class RasterSourceContainer(RasterSource):
    """Container wrapping another raster source."""
    def __init__(self, contained_source): ...

class PostprocessedRasterSource(RasterSourceContainer):
    """Raster source with post-processing step."""
    def __init__(self, contained_source, img_post_process): ...

Shapefile Reading

Access to shapefiles and vector data from various sources.

def natural_earth(resolution='110m', category='physical', name='coastline'):
    """
    Get Natural Earth shapefile path.
    
    Parameters:
    - resolution: str, '110m', '50m', or '10m'
    - category: str, 'physical' or 'cultural'
    - name: str, dataset name
    
    Returns:
    Path to shapefile
    """

def gshhs(scale='c', level=1):
    """
    Get GSHHS coastline shapefile path.
    
    Parameters:
    - scale: str, 'c' (coarse), 'l' (low), 'i' (intermediate), 'h' (high), 'f' (full)
    - level: int, 1-6 (coastline hierarchy level)
    
    Returns:
    Path to shapefile
    """

class Record:
    """Shapefile record interface."""
    @property
    def attributes(self): ...
    @property
    def geometry(self): ...
    @property
    def bounds(self): ...

class BasicReader:
    """Basic shapefile reader."""
    def __init__(self, filename): ...
    def records(self): ...
    def geometries(self): ...
    @property
    def crs(self): ...

class FionaReader(BasicReader):
    """Fiona-based shapefile reader with enhanced capabilities."""
    def __init__(self, filename): ...

def Reader(filename):
    """
    Auto-selecting shapefile reader.
    Returns FionaReader if available, otherwise BasicReader.
    """

Web Tile Services

Access to various web map tile services with caching support.

class GoogleWTS:
    """Abstract base for Google-style web tile services."""
    def __init__(self, cache=False, cache_dir=None, desired_tile_form='RGB'): ...
    def image_for_domain(self, target_domain, target_z): ...

class OSM(GoogleWTS):
    """OpenStreetMap tiles."""
    def __init__(self, cache=False, cache_dir=None, desired_tile_form='RGB'): ...

class GoogleTiles(GoogleWTS):
    """Google Maps tiles."""
    def __init__(self, desired_tile_form='RGB', style='satellite'): ...

class StadiaMapsTiles(GoogleWTS):
    """Stamen map tiles via Stadia Maps."""
    def __init__(self, api_key=None, style='stamen_terrain', 
                 cache=False, cache_dir=None): ...

class MapboxTiles(GoogleWTS):
    """Mapbox tiles."""
    def __init__(self, access_token, map_id='mapbox.satellite'): ...

class MapboxStyleTiles(GoogleWTS):
    """Mapbox style-based tiles."""  
    def __init__(self, access_token, style_id, username='mapbox'): ...

class QuadtreeTiles(GoogleWTS):
    """Generic quadtree tile source."""
    def __init__(self, cache=False, cache_dir=None, desired_tile_form='RGB'): ...

class OrdnanceSurvey(GoogleWTS):
    """UK Ordnance Survey tiles."""
    def __init__(self, api_key, layer='Road', cache=False, cache_dir=None): ...

class Stamen(GoogleWTS):
    """Stamen map tiles (deprecated, use StadiaMapsTiles)."""
    def __init__(self, style='terrain', cache=False, cache_dir=None): ...

class MapQuestOSM(GoogleWTS):
    """MapQuest OpenStreetMap tiles."""
    def __init__(self, cache=False, cache_dir=None): ...

class MapQuestOpenAerial(GoogleWTS):
    """MapQuest aerial imagery tiles."""
    def __init__(self, cache=False, cache_dir=None): ...

Elevation Data (SRTM)

Access to Shuttle Radar Topography Mission elevation data.

class SRTM3Source:
    """SRTM 3 arc-second elevation data source."""
    def __init__(self, max_nx=8, max_ny=8): ...
    def single_tile(self, lon, lat): ...
    def combined(self, extent, nx, ny): ...

class SRTM1Source:
    """SRTM 1 arc-second elevation data source."""
    def __init__(self, max_nx=8, max_ny=8): ...
    def single_tile(self, lon, lat): ...
    def combined(self, extent, nx, ny): ...

def add_shading(elevation, azimuth, altitude):
    """
    Add hillshade effect to elevation data.
    
    Parameters:
    - elevation: 2D array, elevation data
    - azimuth: float, light source azimuth (degrees)
    - altitude: float, light source altitude (degrees)
    
    Returns:
    2D array with hillshade values
    """

def read_SRTM(fh):
    """
    Read SRTM elevation file.
    
    Parameters:
    - fh: file handle or filename
    
    Returns:
    Tuple of (elevation_array, extent)
    """

OGC Web Services

Access to OGC standard web services for maps and features.

class WMSRasterSource(RasterSource):
    """Web Map Service raster source."""
    def __init__(self, wms, layer_names, getmap_extra_kwargs=None): ...
    def validate_projection(self, projection): ...
    def fetch_raster(self, projection, extent, target_resolution): ...

class WMTSRasterSource(RasterSource):
    """Web Map Tile Service raster source."""
    def __init__(self, wmts, layer_name, gettile_extra_kwargs=None): ...
    def validate_projection(self, projection): ...
    def fetch_raster(self, projection, extent, target_resolution): ...

class WFSGeometrySource:
    """Web Feature Service geometry source."""
    def __init__(self, wfs, features): ...
    def default_projection(self): ...
    def fetch_geometries(self, projection, extent=None): ...

Usage Examples

Reading Shapefiles

import cartopy.io.shapereader as shpreader

# Read Natural Earth data
coastline_path = shpreader.natural_earth(
    resolution='50m', 
    category='physical', 
    name='coastline'
)

# Use reader to access geometries and attributes
reader = shpreader.Reader(coastline_path)
for record in reader.records():
    geometry = record.geometry
    attributes = record.attributes
    # Process data...

# Get all geometries
geometries = list(reader.geometries())

Using Web Tile Services

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io import img_tiles

# OpenStreetMap tiles
osm_tiles = img_tiles.OSM()

fig = plt.figure(figsize=(12, 8))
ax = plt.axes(projection=osm_tiles.crs)

# Add tile layer
ax.add_image(osm_tiles, 8)  # Zoom level 8

# Set extent for New York City
ax.set_extent([-74.2, -73.7, 40.5, 40.9])
plt.show()

Working with SRTM Elevation Data

from cartopy.io import srtm
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

# Get elevation data for a region
srtm_source = srtm.SRTM3Source()
lon_extent = (-120, -119)
lat_extent = (36, 37)

# Get combined elevation data
elevation, extent = srtm_source.combined(
    (lon_extent[0], lon_extent[1], lat_extent[0], lat_extent[1]),
    nx=100, ny=100
)

# Add hillshading
shaded_elevation = srtm.add_shading(elevation, azimuth=315, altitude=45)

# Plot
fig = plt.figure(figsize=(12, 8))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.imshow(shaded_elevation, extent=extent, cmap='terrain', 
          transform=ccrs.PlateCarree())
ax.coastlines()

Using OGC Web Services

from owslib.wms import WebMapService
from cartopy.io.ogc_clients import WMSRasterSource

# Connect to WMS service
wms = WebMapService('http://example.com/wms')
wms_source = WMSRasterSource(wms, ['layer_name'])

# Use as raster source with matplotlib
fig = plt.figure(figsize=(12, 8))
ax = plt.axes(projection=ccrs.PlateCarree())

# Fetch and display WMS data
images = wms_source.fetch_raster(
    ccrs.PlateCarree(),
    extent=(-10, 10, 40, 60),
    target_resolution=(800, 600)
)

for img in images:
    ax.imshow(img.image, extent=img.extent, transform=ccrs.PlateCarree())

Custom Downloaders

from cartopy.io import Downloader
from cartopy import config

# Create custom downloader
custom_downloader = Downloader(
    'https://example.com/data/{category}/{name}.zip',
    str(config['data_dir'] / 'custom' / '{category}_{name}.zip')
)

# Register in config
config['downloaders'][('custom', 'dataset')] = custom_downloader

# Use downloader
path = custom_downloader.path({'category': 'geographic', 'name': 'boundaries'})

File Utilities

def fh_getter(fh, mode='r', needs_filename=False):
    """
    Convenience function for opening files.
    
    Parameters:
    - fh: file handle, filename, or (file handle, filename) tuple
    - mode: str, open mode (default 'r')
    - needs_filename: bool, whether filename is required
    
    Returns:
    Tuple of (file_handle, filename)
    """

Exceptions

class DownloadWarning(Warning):
    """Warning issued when downloading files."""

Install with Tessl CLI

npx tessl i tessl/pypi-cartopy

docs

coordinate-systems.md

data-io.md

geodesic.md

geographic-features.md

index.md

matplotlib-integration.md

transformations.md

tile.json