Download module

The download module provides utilities for downloading environmental data from various online sources including CORDEX climate data, Google Earth Engine, Marine Copernicus (ERA5), OpenStreetMap imagery, and Google Maps.

Download module for environmental data acquisition.

This module provides utilities for downloading environmental data from various sources including CORDEX climate data, Google Earth Engine, Marine Copernicus, and satellite imagery.

Submodules:

cordex-data: Download CORDEX climate model data google-earth-engine: Download satellite imagery from Google Earth Engine google-image: Download Google Maps imagery open-street-images: Download OpenStreetMap imagery marine-copernicus: Download marine data from Copernicus Marine Service

class environmentaltools.download.ERA5DataDownloadConfig(config: dict[str, Any] | None = None)[source]

Bases: object

Configuration class for ERA5 data download parameters.

This class accepts configuration as a dictionary and provides validation and default values for all parameters. It supports any ERA5 variable (marine, atmospheric, land, etc.).

dataset_name

CDS dataset identifier.

Type:

str

variable

Variable to download (e.g., wave height, wind, temperature).

Type:

str

start_year

First year to download.

Type:

int

end_year

Last year to download.

Type:

int

area_bounds

Geographic bounds [North, West, South, East].

Type:

list

output_directory

Directory for output files.

Type:

str

file_prefix

Prefix for output filenames.

Type:

str

retry_attempts

Number of retry attempts for failed downloads.

Type:

int

Example

>>> # Download wave data
>>> config_dict = {
...     'start_year': 2015,
...     'end_year': 2020,
...     'area_bounds': [41.4, -9.0, 41.0, -8.65],
...     'output_directory': './era5_data',
...     'variable': 'significant_height_of_combined_wind_waves_and_swell'
... }
>>> config = ERA5DataDownloadConfig(config_dict)
>>>
>>> # Download wind data
>>> config_dict['variable'] = '10m_u_component_of_wind'
>>> config = ERA5DataDownloadConfig(config_dict)
print_summary() None[source]

Print a summary of the current configuration using loguru logger.

class environmentaltools.download.ERA5DataDownloader(config: ERA5DataDownloadConfig)[source]

Bases: object

Main class for downloading ERA5 data from CDS.

This class handles the complete download workflow from any ERA5 dataset (marine, atmospheric, land variables, etc.) with robust error handling and progress tracking.

config

Configuration object.

Type:

ERA5DataDownloadConfig

client

CDS API client for downloads.

Type:

cdsapi.Client

Example

>>> config = ERA5DataDownloadConfig({'start_year': 2018, ...})
>>> downloader = ERA5DataDownloader(config)
>>> results = downloader.download_all_years()
>>> print(f"Downloaded {sum(results.values())} years")
create_download_request(year: str) dict[str, Any][source]

Create CDS API request dictionary for a specific year.

Parameters:

year (str) – Year to download data for

Returns:

CDS API request dictionary

Return type:

Dict[str, Any]

download_all_years() dict[str, bool][source]

Download wave data for all configured years.

Returns:

Dictionary mapping years to download success status

Return type:

Dict[str, bool]

download_year_data(year: str, attempt: int = 1) bool[source]

Download wave data for a specific year with retry logic. Skip download if file already exists and is valid.

Parameters:
  • year (str) – Year to download data for

  • attempt (int, optional) – Current attempt number (default: 1)

Returns:

True if download successful or file already exists, False otherwise

Return type:

bool

generate_output_filename(year: str) str[source]

Generate output filename for a specific year.

Parameters:

year (str) – Year for the filename

Returns:

Complete file path for output

Return type:

str

generate_year_list() list[str][source]

Generate list of years to download based on configuration.

Returns:

List of years as strings

Return type:

list[str]

validate_downloaded_files() dict[str, dict[str, Any]][source]

Validate all downloaded NetCDF files.

Returns:

Dictionary with validation results for each file

Return type:

dict[str, dict[str, Any]]

class environmentaltools.download.ERA5DataProcessor(config: ERA5DataDownloadConfig)[source]

Bases: object

Class for processing downloaded ERA5 data files.

Handles conversion from NetCDF to various formats and data aggregation for any ERA5 variable (marine, atmospheric, etc.).

config

Configuration object.

Type:

ERA5DataDownloadConfig

Example

>>> processor = ERA5DataProcessor(config)
>>> data = processor.load_netcdf_files()
>>> csv_file = processor.export_to_csv(data)
clean_data(data: DataFrame) DataFrame[source]

Clean wave data by removing NaN values and invalid entries.

Parameters:

data (pd.DataFrame) – Raw wave data to clean

Returns:

Cleaned wave data without NaN values

Return type:

pd.DataFrame

export_to_csv(data: DataFrame, filename: str | None = None) str[source]

Export wave data to CSV format in the configured results directory.

Parameters:
  • data (pd.DataFrame) – Wave data to export

  • filename (str, optional) – Output filename (default: from config)

Returns:

Path to the exported CSV file

Return type:

str

Raises:

ValueError – If export fails

load_netcdf_files(file_pattern: str | None = None) DataFrame[source]

Load and concatenate multiple NetCDF files into a pandas DataFrame.

Parameters:

file_pattern (str, optional) – Glob pattern for NetCDF files (default: “*_waves.nc”)

Returns:

Concatenated wave data with time index

Return type:

pd.DataFrame

Raises:
  • FileNotFoundError – If no NetCDF files are found

  • ValueError – If data loading or processing fails

class environmentaltools.download.GoogleMapDownloader(lat: float, lng: float, zoom: int = 12, layer: str = 'v')[source]

Bases: object

Download and stitch Google Maps tiles into high-resolution images.

This class generates high-resolution Google Maps images by downloading and stitching together multiple map tiles based on geographic coordinates and zoom level.

_lat

Latitude of the location.

Type:

float

_lng

Longitude of the location.

Type:

float

_zoom

Zoom level (0-23, where higher values show more detail).

Type:

int

_layer

Map layer type from GoogleMapsLayers.

Type:

str

Example

>>> downloader = GoogleMapDownloader(
...     lat=40.7128,
...     lng=-74.0060,
...     zoom=15,
...     layer=GoogleMapsLayers.SATELLITE
... )
>>> image = downloader.generate_image(tile_width=3, tile_height=3)
>>> image.save("map.png")
generate_image(start_x: int | None = None, start_y: int | None = None, tile_width: int = 5, tile_height: int = 5) Image[source]

Generate high-resolution image by stitching map tiles together.

Downloads individual 256x256 pixel tiles from Google Maps and combines them into a single high-resolution image.

Parameters:
  • start_x (int, optional) – Top-left tile x-coordinate. If None, calculated from lat/lng. Defaults to None.

  • start_y (int, optional) – Top-left tile y-coordinate. If None, calculated from lat/lng. Defaults to None.

  • tile_width (int, optional) – Number of tiles wide (horizontal). Defaults to 5.

  • tile_height (int, optional) – Number of tiles high (vertical). Defaults to 5.

Returns:

PIL Image object containing the stitched map.

Return type:

Image.Image

Raises:
  • IOError – If tile download fails.

  • urllib.error.URLError – If network connection fails.

Example

>>> gmd = GoogleMapDownloader(40.7128, -74.0060, zoom=15)
>>> # Generate 1280x1280 pixel image (5x5 tiles)
>>> img = gmd.generate_image(tile_width=5, tile_height=5)
>>> img.save("output.png")
get_tile_coordinates() tuple[int, int][source]

Calculate tile coordinates from latitude, longitude, and zoom level.

Converts geographic coordinates (lat/lng) to Google Maps tile coordinates using Web Mercator projection.

Returns:

Tile coordinates as (x, y) where x and y are tile

indices at the current zoom level.

Return type:

tuple[int, int]

Example

>>> gmd = GoogleMapDownloader(40.7128, -74.0060, zoom=12)
>>> x, y = gmd.get_tile_coordinates()
>>> print(f"Tile: ({x}, {y})")
class environmentaltools.download.GoogleMapsLayers[source]

Bases: object

Google Maps layer types for tile requests.

ROADMAP

Standard roadmap view with streets and labels.

Type:

str

TERRAIN

Terrain view showing elevation and natural features.

Type:

str

ALTERED_ROADMAP

Alternative roadmap style.

Type:

str

SATELLITE

Satellite imagery without labels.

Type:

str

TERRAIN_ONLY

Terrain-only view without labels.

Type:

str

HYBRID

Satellite imagery with street labels overlay.

Type:

str

ALTERED_ROADMAP = 'r'
HYBRID = 'y'
ROADMAP = 'v'
SATELLITE = 's'
TERRAIN = 'p'
TERRAIN_ONLY = 't'
environmentaltools.download.calculate_extent(lon: float, lat: float, distance_x: float, distance_y: float) list[float][source]

Calculate the geographic extent (bounding box) for a map centered at a location.

This function uses geodesic calculations to determine the map extent based on the center point and distances from the center to the edges.

Parameters:
  • lon – Longitude of the center point in degrees.

  • lat – Latitude of the center point in degrees.

  • distance_x – Distance from center to edge in the x-direction (meters).

  • distance_y – Distance from center to edge in the y-direction (meters).

Returns:

A list of four floats [lon_min, lon_max, lat_min, lat_max] representing the bounding box extent in degrees.

Notes

Uses cartopy’s Geodesic class to accurately calculate positions on the Earth’s surface, accounting for the Earth’s curvature.

environmentaltools.download.calculate_vegetation_indices(image: ee.Image) ee.Image[source]

Calculate vegetation and moisture indices for salt marsh analysis.

Computes three key indices from Sentinel-2 bands: - SAVI: Soil-Adjusted Vegetation Index (reduces soil background effects) - MSI: Moisture Stress Index (indicates plant water stress) - LSWI: Land Surface Water Index (detects surface water content)

Parameters:

image (ee.Image) – Sentinel-2 image with B4 (Red), B8 (NIR), and B11 (SWIR1) bands.

Returns:

Image with selected bands (B4, B8, B11) plus calculated

indices (SAVI, MSI, LSWI) and QA60 quality band.

Return type:

ee.Image

Note

SAVI uses L=0.5 for moderate vegetation coverage typical in salt marshes.

Example

>>> sentinel_image = ee.Image("COPERNICUS/S2_HARMONIZED/...")
>>> with_indices = calculate_vegetation_indices(sentinel_image)
environmentaltools.download.create_osm_image(lon: float, lat: float, site_name: str = 'Location', style: Literal['map', 'satellite'] = 'satellite', distance_x: float = 500, distance_y: float = 500, output_file: str | None = None, show_plot: bool = True) None[source]

Create and display an OpenStreetMap image with customizable style and extent.

This function downloads OpenStreetMap tiles (either satellite imagery or street map) and displays them using matplotlib with cartopy projections. The zoom level is automatically calculated based on the requested extent.

Parameters:
  • lon – Longitude of the center point in degrees.

  • lat – Latitude of the center point in degrees.

  • site_name – Name of the site/location for the plot title. Default is “Location”.

  • style – Map style, either ‘map’ for street map or ‘satellite’ for satellite imagery. Default is ‘satellite’.

  • distance_x – Distance from center to edge in the x-direction (meters). Default is 500.

  • distance_y – Distance from center to edge in the y-direction (meters). Default is 500.

  • output_file – Path to save the image file. If None, image is not saved. Supported formats: .png, .jpg, .jpeg, .pdf, .svg, .eps

  • show_plot – Whether to display the plot interactively. Default is True.

Returns:

None. Displays and/or saves the map.

Notes

  • Scale (zoom level) is automatically calculated based on the maximum distance.

  • According to OSM policies, avoid both large scale (>16) and large radius (>1000).

  • Scale guidelines:
    • 2: Coarse image for worldwide or continental scales

    • 4-6: Medium coarseness for countries and larger states

    • 6-10: Medium fineness for smaller states, regions, and cities

    • 10-12: Fine image for city boundaries and zip codes

    • 14+: Extremely fine image for roads, blocks, buildings

References

OSM Tile Usage Policy: https://operations.osmfoundation.org/policies/tiles/

environmentaltools.download.create_sentinel2_collection(study_area: ee.Geometry, start_date: str = '2015-01-01', end_date: str = '2024-01-01', cloud_percentage: float = 15.0) ee.ImageCollection[source]

Create filtered Sentinel-2 image collection with vegetation indices.

Filters Sentinel-2 imagery based on spatial extent, date range, and cloud cover, then calculates vegetation indices for each image.

Parameters:
  • study_area (ee.Geometry) – Geographic area of interest.

  • start_date (str, optional) – Start date in ‘YYYY-MM-DD’ format. Defaults to “2015-01-01”.

  • end_date (str, optional) – End date in ‘YYYY-MM-DD’ format. Defaults to “2024-01-01”.

  • cloud_percentage (float, optional) – Maximum cloud cover percentage. Defaults to 15.0.

Returns:

Filtered collection with vegetation indices.

Return type:

ee.ImageCollection

Raises:

ValueError – If no images match the filtering criteria.

Example

>>> area = ee.Geometry.Point([-6.0, 36.8]).buffer(10000)
>>> collection = create_sentinel2_collection(area, "2020-01-01", "2020-12-31")
environmentaltools.download.create_study_area_geometry(coordinates: list[list[list[float]]]) ee.Geometry[source]

Create Earth Engine geometry from coordinate list.

Parameters:

coordinates (list) – Nested list of coordinates defining polygon vertices. Format: [[[lon1, lat1], [lon2, lat2], …]]

Returns:

Earth Engine polygon geometry.

Return type:

ee.Geometry

Example

>>> coords = [[[-6.1, 36.8], [-6.0, 36.8], [-6.0, 36.9], [-6.1, 36.9]]]
>>> geometry = create_study_area_geometry(coords)
environmentaltools.download.descargar_copernicus(dataset_id, dataset_version, variables, coords, fechas, output_path)[source]

Función estable para descarga de datos de oleaje.

Parameters:
  • dataset_id (str) – Identifier of the Copernicus dataset.

  • dataset_version (str) – Version of the dataset to be downloaded.

  • variables (list) – List of variables to include in the subset.

  • coords (dict) – Dictionary containing spatial limits (‘lon_min’, ‘lon_max’, ‘lat_min’, ‘lat_max’).

  • fechas (dict) – Dictionary with time range (‘inicio’, ‘fin’).

  • output_path (str) – Directory path where the file will be saved.

Returns:

None

environmentaltools.download.download_era5_data(config: dict[str, Any]) dict[str, Any][source]

Download and process ERA5 data from Climate Data Store.

Main function that orchestrates the complete workflow for downloading and processing ERA5 data. Accepts a configuration dictionary and returns processing results including download statistics and output file paths.

Parameters:

config (dict) – Configuration dictionary with keys: - start_year (int): First year to download (required) - end_year (int): Last year to download (required) - area_bounds (list): Geographic bounds [North, West, South, East] (required) - output_directory (str): Directory for output files (required) - variable (str, optional): CDS variable name - file_prefix (str, optional): Prefix for output filenames - export_csv (bool, optional): Export data to CSV format (default: True)

Returns:

Results dictionary containing:
  • config (ERA5DataDownloadConfig): Configuration object used

  • download_results (dict): Download status for each year

  • validation_results (dict): Validation status for each file

  • data (pd.DataFrame): Processed data

  • csv_path (str, optional): Path to exported CSV file

Return type:

dict

Raises:
  • ValueError – If required configuration parameters are missing or invalid.

  • ConnectionError – If CDS API client cannot be initialized.

Example

>>> from environmentaltools.download import marine_copernicus
>>>
>>> # Define configuration
>>> config = {
...     'start_year': 2018,
...     'end_year': 2020,
...     'area_bounds': [41.4, -9.0, 41.0, -8.65],
...     'output_directory': './era5_data',
...     'variable': 'significant_height_of_combined_wind_waves_and_swell',
...     'export_csv': True
... }
>>>
>>> # Download and process data
>>> results = marine_copernicus.download_era5_data(config)
>>> print(f"Downloaded {results['download_results']} years")
>>> print(f"Data saved to: {results['csv_path']}")
environmentaltools.download.download_esgf_dataset(dataset_metadata: Dict, output_folder: str, file_filter: str | None = None, **kwargs) List[str][source]

Download ESGF dataset with automatic implementation selection.

Parameters:
  • dataset_metadata – Dataset metadata from query_esgf_catalog

  • output_folder – Directory to save downloaded files

  • file_filter – Optional filter for specific files

  • **kwargs – Additional arguments

Returns:

List of downloaded file paths

Return type:

List[str]

environmentaltools.download.download_esgf_dataset_intake(dataset_id: str, indices: List[str] | None = None, auth: Dict[str, str] | None = None, chunks: Dict[str, int] | None = None, **kwargs) Tuple[Dataset, List[str]][source]

Download ESGF dataset using intake-esgf.

Modern replacement for download_esgf_dataset using intake-esgf package. Provides better authentication handling and connection reliability.

Parameters:
  • dataset_id – ESGF dataset ID to download

  • indices – List of ESGF indices to try. If None, uses defaults

  • auth – Authentication dictionary with ‘username’ and ‘password’ keys

  • chunks – Chunking specification for xarray, e.g., {‘time’: 100}

  • **kwargs – Additional parameters for intake-esgf

Returns:

  • Dataset: xarray Dataset with the climate data

  • URLs: List of access URLs used

Return type:

Tuple containing

Raises:
  • ImportError – If intake-esgf is not installed

  • ConnectionError – If unable to download from any index

Example

>>> auth = {'username': 'user', 'password': 'pass'}
>>> ds, urls = download_esgf_dataset_intake(
...     "cordex.output.EUR-11.SMHI...",
...     auth=auth
... )
environmentaltools.download.download_google_maps_image(lat: float, lng: float, zoom: int = 13, layer: str = 's', tile_width: int = 5, tile_height: int = 5, output_file: str = 'google_maps_image.png') bool[source]

Download and save a Google Maps image for specified coordinates.

Convenience function that creates a GoogleMapDownloader, generates an image, and saves it to disk.

Parameters:
  • lat (float) – Latitude of center location in decimal degrees.

  • lng (float) – Longitude of center location in decimal degrees.

  • zoom (int, optional) – Zoom level (0-23). Defaults to 13.

  • layer (str, optional) – Map layer type. Defaults to GoogleMapsLayers.SATELLITE.

  • tile_width (int, optional) – Number of tiles wide. Defaults to 5.

  • tile_height (int, optional) – Number of tiles high. Defaults to 5.

  • output_file (str, optional) – Output filename. Defaults to “google_maps_image.png”.

Returns:

True if successful, False otherwise.

Return type:

bool

Example

>>> # Download satellite image of New York City
>>> success = download_google_maps_image(
...     lat=40.7128,
...     lng=-74.0060,
...     zoom=15,
...     layer=GoogleMapsLayers.SATELLITE,
...     tile_width=3,
...     tile_height=3,
...     output_file="nyc_satellite.png"
... )
>>> if success:
...     print("Map downloaded successfully")
environmentaltools.download.download_image_with_geemap(image: ee.Image, output_file: Path, study_area: ee.Geometry, scale: int = 10) bool[source]

Download Earth Engine image to GeoTIFF using geemap.

Uses geemap’s download function to export an Earth Engine image to a local file. Validates that the downloaded file exists and has reasonable size.

Parameters:
  • image (ee.Image) – Earth Engine image to download.

  • output_file (Path) – Output file path for the GeoTIFF.

  • study_area (ee.Geometry) – Study area for clipping the image.

  • scale (int, optional) – Spatial resolution in meters. Defaults to 10 (Sentinel-2 native resolution).

Returns:

True if download successful and validated, False otherwise.

Return type:

bool

Example

>>> img = ee.Image("COPERNICUS/S2_HARMONIZED/20200601T105619_20200601T110145_T30STG")
>>> area = ee.Geometry.Point([-6.0, 36.8]).buffer(10000)
>>> success = download_image_with_geemap(img, Path("output.tif"), area)
environmentaltools.download.download_openstreet_map(lon: float, lat: float, distance_x: float, distance_y: float, site_name: str, style: Literal['map', 'satellite'] = 'satellite', output_file: str | None = None, show_plot: bool = True) None[source]

Download and display OpenStreetMap image for a specified location.

This is a convenience wrapper function for creating OpenStreetMap visualizations with either satellite imagery or street map style.

Parameters:
  • lon – Longitude of the center point in degrees.

  • lat – Latitude of the center point in degrees.

  • distance_x – Distance from center to edge in the x-direction (meters).

  • distance_y – Distance from center to edge in the y-direction (meters).

  • site_name – Name of the site/location for the plot title.

  • style – Map style, either ‘map’ for street map or ‘satellite’ for satellite imagery. Default is ‘satellite’.

  • output_file – Path to save the image file. If None, image is not saved. Supported formats: .png, .jpg, .jpeg, .pdf, .svg, .eps

  • show_plot – Whether to display the plot interactively. Default is True.

Returns:

None. Displays and/or saves the map.

Example

>>> # Display and save satellite image
>>> download_openstreet_map(
...     lon=-3.7038,
...     lat=40.4168,
...     distance_x=500,
...     distance_y=500,
...     site_name="Madrid",
...     style="satellite",
...     output_file="madrid_satellite.png",
...     show_plot=True
... )
>>>
>>> # Save only (no display)
>>> download_openstreet_map(
...     lon=-3.7038,
...     lat=40.4168,
...     distance_x=500,
...     distance_y=500,
...     site_name="Madrid",
...     style="map",
...     output_file="madrid_map.png",
...     show_plot=False
... )
environmentaltools.download.download_sentinel2_images(config: dict[str, Any]) dict[str, int][source]

Download time series of Sentinel-2 imagery with vegetation indices.

Main function that orchestrates the complete download workflow: initialization, collection creation, and batch downloading of images.

Parameters:

config (dict) – Configuration dictionary containing: - project_id (str): Google Earth Engine project ID - study_area_coords (list): Coordinates defining the study area polygon - output_directory (str or Path): Directory for output files - scale (int, optional): Spatial resolution in meters. Default: 10 - start_date (str, optional): Start date ‘YYYY-MM-DD’. Default: “2015-01-01” - end_date (str, optional): End date ‘YYYY-MM-DD’. Default: “2024-01-01” - cloud_percentage (float, optional): Max cloud cover %. Default: 15.0

Returns:

Summary statistics with keys:
  • successful (int): Number of successful downloads

  • failed (int): Number of failed downloads

  • total (int): Total number of images processed

Return type:

dict

Raises:
  • RuntimeError – If Earth Engine initialization fails.

  • ValueError – If no images match the filtering criteria.

Example

>>> config = {
...     'project_id': 'my-gee-project',
...     'study_area_coords': [[[-6.1, 36.8], [-6.0, 36.8], ...]],
...     'output_directory': './satellite_images',
...     'scale': 10,
...     'start_date': '2020-01-01',
...     'end_date': '2020-12-31',
...     'cloud_percentage': 10.0
... }
>>> results = download_sentinel2_images(config)
>>> print(f"Downloaded {results['successful']} images")
environmentaltools.download.download_single_sentinel2_image(image_info: dict[str, Any], image_index: int, total_images: int, collection: ee.ImageCollection, study_area: ee.Geometry, output_directory: Path, scale: int = 10) bool[source]

Download a single Sentinel-2 image with vegetation indices.

Extracts an image from a collection, clips it to the study area, and downloads it using geemap. Skips download if file already exists.

Parameters:
  • image_info (dict) – Image metadata from Earth Engine containing properties like ‘system:index’ and ‘system:time_start’.

  • image_index (int) – Current image index (for progress tracking).

  • total_images (int) – Total number of images to process.

  • collection (ee.ImageCollection) – Pre-created collection containing the image.

  • study_area (ee.Geometry) – Study area geometry for clipping.

  • output_directory (Path) – Directory where files will be saved.

  • scale (int, optional) – Spatial resolution in meters. Defaults to 10.

Returns:

True if download successful or file exists, False otherwise.

Return type:

bool

Example

>>> info = {'properties': {'system:index': 'T30STG_20200601', ...}}
>>> success = download_single_sentinel2_image(
...     info, 0, 10, collection, area, Path("./output")
... )
environmentaltools.download.download_with_config(output_folder: str, config_file: str = 'download_config.ini') List[str][source]

Download ESGF data using configuration file with automatic implementation selection.

Parameters:
  • output_folder – Directory to save downloaded files

  • config_file – Path to configuration file

Returns:

List of downloaded file paths

Return type:

List[str]

environmentaltools.download.download_with_config_intake(output_folder: str, auth_config: str | None = None) None[source]

Download CORDEX data using configuration files with intake-esgf.

Modern replacement for download_with_config using intake-esgf package. Maintains the same interface but uses the updated backend.

Parameters:
  • output_folder – Directory path where files will be stored

  • auth_config – Path to authentication config file. If None, uses ~/.esgf/config.ini

Raises:
  • ImportError – If intake-esgf is not installed

  • FileNotFoundError – If required configuration files are missing

Note

Expects the same file structure as the original function: - coordinates.csv: Coordinate points - selection.csv: Dataset selection indices - queries.xlsx: Available dataset queries

environmentaltools.download.initialize_earth_engine(project_id: str) None[source]

Initialize Google Earth Engine with authentication.

Attempts to initialize Earth Engine with existing credentials. If that fails, triggers the authentication flow and then initializes.

Parameters:

project_id (str) – Google Earth Engine project ID.

Raises:

RuntimeError – If Earth Engine initialization fails after authentication.

Example

>>> initialize_earth_engine("my-gee-project")
Earth Engine initialized successfully
environmentaltools.download.query_esgf_catalog(query: Dict[str, str | List[str]], indices: List[str] | None = None, **kwargs) DataFrame[source]

Query ESGF catalog with automatic fallback for CORDEX projects.

Uses intake-esgf for supported projects, falls back to PyESGF for CORDEX.

Parameters:
  • query – Dictionary of query parameters

  • indices – List of ESGF indices to search

  • **kwargs – Additional arguments

Returns:

DataFrame containing metadata for matching datasets

Return type:

pd.DataFrame

Raises:

ImportError – If neither intake-esgf nor PyESGF is available

environmentaltools.download.query_esgf_catalog_intake(query: Dict[str, str | List[str]], indices: List[str] | None = None, **kwargs) DataFrame[source]

Query ESGF catalog using intake-esgf.

Modern replacement for query_esgf_catalog using intake-esgf package. Provides better performance and compatibility with current ESGF infrastructure.

Parameters:
  • query – Dictionary of CORDEX query parameters. Common keys include: - project (str): e.g., “CORDEX” - domain (str): e.g., “EUR-11” - experiment (str): e.g., “rcp85” - time_frequency (str): e.g., “3hr”, “day”, “mon” - variable (list): e.g., [“pr”, “tas”]

  • indices – List of ESGF indices to search. If None, uses default indices. Defaults to None.

  • **kwargs – Additional query parameters

Returns:

DataFrame containing metadata for all matching datasets.

Return type:

pd.DataFrame

Raises:
  • ImportError – If intake-esgf is not installed

  • ConnectionError – If unable to connect to any ESGF index

Example

>>> query = {"project": "CORDEX", "domain": "EUR-11", "variable": ["pr"]}
>>> datasets = query_esgf_catalog_intake(query)
>>> print(f"Found {len(datasets)} datasets")

CORDEX Data

Functions for downloading CORDEX climate model data from ESGF nodes.

query_esgf_catalog(query[, indices])

Query ESGF catalog with automatic fallback for CORDEX projects.

download_esgf_dataset(dataset_metadata, ...)

Download ESGF dataset with automatic implementation selection.

download_with_config(output_folder[, ...])

Download ESGF data using configuration file with automatic implementation selection.

Google Earth Engine

Functions for downloading satellite imagery from Google Earth Engine.

initialize_earth_engine(project_id)

Initialize Google Earth Engine with authentication.

create_study_area_geometry(coordinates)

Create Earth Engine geometry from coordinate list.

calculate_vegetation_indices(image)

Calculate vegetation and moisture indices for salt marsh analysis.

create_sentinel2_collection(study_area[, ...])

Create filtered Sentinel-2 image collection with vegetation indices.

download_image_with_geemap(image, ...[, scale])

Download Earth Engine image to GeoTIFF using geemap.

download_single_sentinel2_image(image_info, ...)

Download a single Sentinel-2 image with vegetation indices.

download_sentinel2_images(config)

Download time series of Sentinel-2 imagery with vegetation indices.

Google Maps

Classes and functions for downloading Google Maps imagery.

Classes

GoogleMapsLayers()

Google Maps layer types for tile requests.

GoogleMapDownloader(lat, lng[, zoom, layer])

Download and stitch Google Maps tiles into high-resolution images.

Functions

download_google_maps_image(lat, lng[, zoom, ...])

Download and save a Google Maps image for specified coordinates.

OpenStreetMap

Functions for downloading and visualizing OpenStreetMap imagery.

download_openstreet_map(lon, lat, ...[, ...])

Download and display OpenStreetMap image for a specified location.

create_osm_image(lon, lat[, site_name, ...])

Create and display an OpenStreetMap image with customizable style and extent.

calculate_extent(lon, lat, distance_x, ...)

Calculate the geographic extent (bounding box) for a map centered at a location.

Marine Copernicus (ERA5)

Classes and functions for downloading ERA5 reanalysis data from the Copernicus Climate Data Store.

Configuration

ERA5DataDownloadConfig([config])

Configuration class for ERA5 data download parameters.

Download

ERA5DataDownloader(config)

Main class for downloading ERA5 data from CDS.

Processing

ERA5DataProcessor(config)

Class for processing downloaded ERA5 data files.

Main Functions

download_era5_data(config)

Download and process ERA5 data from Climate Data Store.

Marine Copernicus (Projections)

Classes and functions for downloading projections data from the Copernicus Climate Data Store.

Configuration

ProjectionDataConfig(config)

Configuración estructurada para Proyecciones Climáticas.

Download

ProjectionDownloader(config)

Manejador de descargas para el Climate Data Store.

Processing

ProjectionProcessor(config)

Clase para procesar, filtrar y visualizar proyecciones climáticas de oleaje.

Copernicus Marine (General)

Main Functions

descargar_copernicus(dataset_id, ...)

Función estable para descarga de datos de oleaje.