or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

coordinate-systems.mddata-io.mdgeodesic.mdgeographic-features.mdindex.mdmatplotlib-integration.mdtransformations.md

data-io.mddocs/

0

# Data Input/Output

1

2

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.

3

4

## Capabilities

5

6

### Base IO Classes

7

8

Core classes for handling data downloads and raster sources.

9

10

```python { .api }

11

class Downloader:

12

"""Resource downloader with caching and automatic acquisition."""

13

def __init__(self, url_template, target_path_template,

14

pre_downloaded_path_template=''): ...

15

def url(self, format_dict): ...

16

def target_path(self, format_dict): ...

17

def pre_downloaded_path(self, format_dict): ...

18

def path(self, format_dict): ...

19

def acquire_resource(self, target_path, format_dict): ...

20

@staticmethod

21

def from_config(specification, config_dict=None): ...

22

23

class LocatedImage:

24

"""Image with associated spatial extent."""

25

image: Any

26

extent: Tuple[float, float, float, float]

27

28

class RasterSource:

29

"""Abstract interface for raster data sources."""

30

def validate_projection(self, projection): ...

31

def fetch_raster(self, projection, extent, target_resolution): ...

32

33

class RasterSourceContainer(RasterSource):

34

"""Container wrapping another raster source."""

35

def __init__(self, contained_source): ...

36

37

class PostprocessedRasterSource(RasterSourceContainer):

38

"""Raster source with post-processing step."""

39

def __init__(self, contained_source, img_post_process): ...

40

```

41

42

### Shapefile Reading

43

44

Access to shapefiles and vector data from various sources.

45

46

```python { .api }

47

def natural_earth(resolution='110m', category='physical', name='coastline'):

48

"""

49

Get Natural Earth shapefile path.

50

51

Parameters:

52

- resolution: str, '110m', '50m', or '10m'

53

- category: str, 'physical' or 'cultural'

54

- name: str, dataset name

55

56

Returns:

57

Path to shapefile

58

"""

59

60

def gshhs(scale='c', level=1):

61

"""

62

Get GSHHS coastline shapefile path.

63

64

Parameters:

65

- scale: str, 'c' (coarse), 'l' (low), 'i' (intermediate), 'h' (high), 'f' (full)

66

- level: int, 1-6 (coastline hierarchy level)

67

68

Returns:

69

Path to shapefile

70

"""

71

72

class Record:

73

"""Shapefile record interface."""

74

@property

75

def attributes(self): ...

76

@property

77

def geometry(self): ...

78

@property

79

def bounds(self): ...

80

81

class BasicReader:

82

"""Basic shapefile reader."""

83

def __init__(self, filename): ...

84

def records(self): ...

85

def geometries(self): ...

86

@property

87

def crs(self): ...

88

89

class FionaReader(BasicReader):

90

"""Fiona-based shapefile reader with enhanced capabilities."""

91

def __init__(self, filename): ...

92

93

def Reader(filename):

94

"""

95

Auto-selecting shapefile reader.

96

Returns FionaReader if available, otherwise BasicReader.

97

"""

98

```

99

100

### Web Tile Services

101

102

Access to various web map tile services with caching support.

103

104

```python { .api }

105

class GoogleWTS:

106

"""Abstract base for Google-style web tile services."""

107

def __init__(self, cache=False, cache_dir=None, desired_tile_form='RGB'): ...

108

def image_for_domain(self, target_domain, target_z): ...

109

110

class OSM(GoogleWTS):

111

"""OpenStreetMap tiles."""

112

def __init__(self, cache=False, cache_dir=None, desired_tile_form='RGB'): ...

113

114

class GoogleTiles(GoogleWTS):

115

"""Google Maps tiles."""

116

def __init__(self, desired_tile_form='RGB', style='satellite'): ...

117

118

class StadiaMapsTiles(GoogleWTS):

119

"""Stamen map tiles via Stadia Maps."""

120

def __init__(self, api_key=None, style='stamen_terrain',

121

cache=False, cache_dir=None): ...

122

123

class MapboxTiles(GoogleWTS):

124

"""Mapbox tiles."""

125

def __init__(self, access_token, map_id='mapbox.satellite'): ...

126

127

class MapboxStyleTiles(GoogleWTS):

128

"""Mapbox style-based tiles."""

129

def __init__(self, access_token, style_id, username='mapbox'): ...

130

131

class QuadtreeTiles(GoogleWTS):

132

"""Generic quadtree tile source."""

133

def __init__(self, cache=False, cache_dir=None, desired_tile_form='RGB'): ...

134

135

class OrdnanceSurvey(GoogleWTS):

136

"""UK Ordnance Survey tiles."""

137

def __init__(self, api_key, layer='Road', cache=False, cache_dir=None): ...

138

139

class Stamen(GoogleWTS):

140

"""Stamen map tiles (deprecated, use StadiaMapsTiles)."""

141

def __init__(self, style='terrain', cache=False, cache_dir=None): ...

142

143

class MapQuestOSM(GoogleWTS):

144

"""MapQuest OpenStreetMap tiles."""

145

def __init__(self, cache=False, cache_dir=None): ...

146

147

class MapQuestOpenAerial(GoogleWTS):

148

"""MapQuest aerial imagery tiles."""

149

def __init__(self, cache=False, cache_dir=None): ...

150

```

151

152

### Elevation Data (SRTM)

153

154

Access to Shuttle Radar Topography Mission elevation data.

155

156

```python { .api }

157

class SRTM3Source:

158

"""SRTM 3 arc-second elevation data source."""

159

def __init__(self, max_nx=8, max_ny=8): ...

160

def single_tile(self, lon, lat): ...

161

def combined(self, extent, nx, ny): ...

162

163

class SRTM1Source:

164

"""SRTM 1 arc-second elevation data source."""

165

def __init__(self, max_nx=8, max_ny=8): ...

166

def single_tile(self, lon, lat): ...

167

def combined(self, extent, nx, ny): ...

168

169

def add_shading(elevation, azimuth, altitude):

170

"""

171

Add hillshade effect to elevation data.

172

173

Parameters:

174

- elevation: 2D array, elevation data

175

- azimuth: float, light source azimuth (degrees)

176

- altitude: float, light source altitude (degrees)

177

178

Returns:

179

2D array with hillshade values

180

"""

181

182

def read_SRTM(fh):

183

"""

184

Read SRTM elevation file.

185

186

Parameters:

187

- fh: file handle or filename

188

189

Returns:

190

Tuple of (elevation_array, extent)

191

"""

192

```

193

194

### OGC Web Services

195

196

Access to OGC standard web services for maps and features.

197

198

```python { .api }

199

class WMSRasterSource(RasterSource):

200

"""Web Map Service raster source."""

201

def __init__(self, wms, layer_names, getmap_extra_kwargs=None): ...

202

def validate_projection(self, projection): ...

203

def fetch_raster(self, projection, extent, target_resolution): ...

204

205

class WMTSRasterSource(RasterSource):

206

"""Web Map Tile Service raster source."""

207

def __init__(self, wmts, layer_name, gettile_extra_kwargs=None): ...

208

def validate_projection(self, projection): ...

209

def fetch_raster(self, projection, extent, target_resolution): ...

210

211

class WFSGeometrySource:

212

"""Web Feature Service geometry source."""

213

def __init__(self, wfs, features): ...

214

def default_projection(self): ...

215

def fetch_geometries(self, projection, extent=None): ...

216

```

217

218

## Usage Examples

219

220

### Reading Shapefiles

221

222

```python

223

import cartopy.io.shapereader as shpreader

224

225

# Read Natural Earth data

226

coastline_path = shpreader.natural_earth(

227

resolution='50m',

228

category='physical',

229

name='coastline'

230

)

231

232

# Use reader to access geometries and attributes

233

reader = shpreader.Reader(coastline_path)

234

for record in reader.records():

235

geometry = record.geometry

236

attributes = record.attributes

237

# Process data...

238

239

# Get all geometries

240

geometries = list(reader.geometries())

241

```

242

243

### Using Web Tile Services

244

245

```python

246

import matplotlib.pyplot as plt

247

import cartopy.crs as ccrs

248

from cartopy.io import img_tiles

249

250

# OpenStreetMap tiles

251

osm_tiles = img_tiles.OSM()

252

253

fig = plt.figure(figsize=(12, 8))

254

ax = plt.axes(projection=osm_tiles.crs)

255

256

# Add tile layer

257

ax.add_image(osm_tiles, 8) # Zoom level 8

258

259

# Set extent for New York City

260

ax.set_extent([-74.2, -73.7, 40.5, 40.9])

261

plt.show()

262

```

263

264

### Working with SRTM Elevation Data

265

266

```python

267

from cartopy.io import srtm

268

import matplotlib.pyplot as plt

269

import cartopy.crs as ccrs

270

271

# Get elevation data for a region

272

srtm_source = srtm.SRTM3Source()

273

lon_extent = (-120, -119)

274

lat_extent = (36, 37)

275

276

# Get combined elevation data

277

elevation, extent = srtm_source.combined(

278

(lon_extent[0], lon_extent[1], lat_extent[0], lat_extent[1]),

279

nx=100, ny=100

280

)

281

282

# Add hillshading

283

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

284

285

# Plot

286

fig = plt.figure(figsize=(12, 8))

287

ax = plt.axes(projection=ccrs.PlateCarree())

288

ax.imshow(shaded_elevation, extent=extent, cmap='terrain',

289

transform=ccrs.PlateCarree())

290

ax.coastlines()

291

```

292

293

### Using OGC Web Services

294

295

```python

296

from owslib.wms import WebMapService

297

from cartopy.io.ogc_clients import WMSRasterSource

298

299

# Connect to WMS service

300

wms = WebMapService('http://example.com/wms')

301

wms_source = WMSRasterSource(wms, ['layer_name'])

302

303

# Use as raster source with matplotlib

304

fig = plt.figure(figsize=(12, 8))

305

ax = plt.axes(projection=ccrs.PlateCarree())

306

307

# Fetch and display WMS data

308

images = wms_source.fetch_raster(

309

ccrs.PlateCarree(),

310

extent=(-10, 10, 40, 60),

311

target_resolution=(800, 600)

312

)

313

314

for img in images:

315

ax.imshow(img.image, extent=img.extent, transform=ccrs.PlateCarree())

316

```

317

318

### Custom Downloaders

319

320

```python

321

from cartopy.io import Downloader

322

from cartopy import config

323

324

# Create custom downloader

325

custom_downloader = Downloader(

326

'https://example.com/data/{category}/{name}.zip',

327

str(config['data_dir'] / 'custom' / '{category}_{name}.zip')

328

)

329

330

# Register in config

331

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

332

333

# Use downloader

334

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

335

```

336

337

## File Utilities

338

339

```python { .api }

340

def fh_getter(fh, mode='r', needs_filename=False):

341

"""

342

Convenience function for opening files.

343

344

Parameters:

345

- fh: file handle, filename, or (file handle, filename) tuple

346

- mode: str, open mode (default 'r')

347

- needs_filename: bool, whether filename is required

348

349

Returns:

350

Tuple of (file_handle, filename)

351

"""

352

```

353

354

## Exceptions

355

356

```python { .api }

357

class DownloadWarning(Warning):

358

"""Warning issued when downloading files."""

359

```