landsatxplore

repository·master·Indexed 42 days ago

https://github.com/yannforget/landsatxplore

A Python package and CLI for searching and downloading Landsat satellite imagery from the USGS EarthExplorer portal. Version 0.15.0 provides a high-level API for scene discovery based on location, date, and cloud cover, as well as tools for downloading scenes and managing EarthExplorer credentials.

Tokens
6.1K
Snippets
23
Records
28
Agent score
53%

What's inside landsatxplore

  1. Configure EarthExplorer credentials

    master

    To use landsatxplore, you must have Earth Explorer credentials. You can provide your username and password via command-line options (--username, --password) or by setting the following environment variables:

    export LANDSATXPLORE_USERNAME=<your_username>
    export LANDSATXPLORE_PASSWORD=<your_password>
  2. Handle landsatxplore error hierarchy

    master

    When working with landsatxplore, you should catch exceptions using the following hierarchy to handle different failure modes:

    1. LandsatxploreError: The base exception for all errors raised by the library. Catching this will catch any error originating from the package.
    2. EarthExplorerError: Specifically for errors raised by the Earth Explorer API.
    3. USGSError: A general error related to the USGS API. This is a parent to more specific USGS errors:
      • USGSInvalidEndpoint: The requested endpoint is invalid.
      • USGSInvalidParametersError: The parameters provided in the request are invalid.
      • USGSUnauthorizedError: The user lacks access to the requested endpoint.
      • USGSAuthenticationError: Credentials verification failed or the API key is invalid.
      • USGSRateLimitError: The account is being rate-limited (does not support multiple concurrent requests).
  3. Initialize the EarthExplorer API

    master

    To interact with the USGS M2M API, instantiate the API class with your USGS EarthExplorer credentials. The constructor automatically performs a login to obtain an access token.

    from landsatxplore.api import API
    
    api = API(username='your_username', password='your_password')
  4. Search for scenes using the Python API

    master

    The API.search() method provides a high-level way to search for scenes using common parameters like dataset, latitude, longitude, start_date, end_date, and max_cloud_cover.

    import json
    from landsatxplore.api import API
    
    api = API(username, password)
    
    # Search for Landsat TM scenes
    scenes = api.search(
        dataset='landsat_tm_c2_l1',
        latitude=50.85,
        longitude=-4.35,
        start_date='1995-01-01',
        end_date='1995-10-01',
        max_cloud_cover=10
    )
    
    print(f"{len(scenes)} scenes found.")
    
    for scene in scenes:
        print(scene['acquisition_date'].strftime('%Y-%m-%d'))
        # Example: Write scene footprints to disk
        fname = f"{scene['landsat_product_id']}.geojson"
        with open(fname, "w") as f:
            json.dump(scene['spatial_coverage'].__geo_interface__, f)
    
    api.logout()
  5. Use the EarthExplorer API for searching and requests

    master

    The landsatxplore.api.API class provides a low-level interface to the Earth Explorer JSON API. You can initialize an instance with your credentials, perform arbitrary requests to endpoints, and then log out.

    Workflow:

    1. Initialize API(username, password).
    2. Call api.request(endpoint, params={...}) to interact with the JSON API.
    3. Call api.logout() to end the session.
    from landsatxplore.api import API
    
    api = API(username, password)
    response = api.request(
        '<request_endpoint>',
        params={
            "param_1": value_1,
            "param_2": value_2
        }
    )
    api.logout()
  6. Download scenes using the EarthExplorer class

    master

    The landsatxplore.earthexplorer.EarthExplorer class is a high-level wrapper designed specifically for downloading scenes.

    from landsatxplore.earthexplorer import EarthExplorer
    
    ee = EarthExplorer(username, password)
    
    ee.download('LT51960471995178MPS00', output_dir='./data')
    
    ee.logout()
  7. Reference: Supported Landsat Datasets

    master

    The following dataset IDs are supported by the package:

    Dataset NameDataset ID
    Landsat 5 TM Collection 2 Level 1landsat_tm_c2_l1
    Landsat 5 TM Collection 2 Level 2landsat_tm_c2_l2
    Landsat 7 ETM+ Collection 2 Level 1landsat_etm_c2_l1
    Landsat 7 ETM+ Collection 2 Level 2landsat_etm_c2_l2
    Landsat 8 Collection 2 Level 1landsat_ot_c2_l1
    Landsat 8 Collection 2 Level 2landsat_ot_c2_l2
    Landsat 9 Collection 2 Level 1landsat_ot_c2_l1
    Landsat 9 Collection 2 Level 2landsat_ot_c2_l2
  8. Handle USGS API errors and rate limits

    master

    The API class automatically handles certain error types and rate limits:

    • Rate Limiting: If a RATE_LIMIT error is encountered, the client will automatically sleep for 3 seconds and retry the request once.
    • Authentication Errors: Raises USGSAuthenticationError for invalid or unauthorized credentials (AUTH_INVALID, AUTH_UNAUTHROIZED, AUTH_KEY_INVALID).
    • General Errors: Raises USGSError for other non-null error codes returned by the API.

    Ensure you catch these exceptions in your application logic to handle session expiration or service outages.

  9. Search for Landsat scenes via CLI

    master

    Use the landsatxplore search command to find scenes based on dataset, location, date range, and cloud cover.

    Common Options:

    • -d, --dataset: The Landsat dataset ID.
    • -l, --location: Latitude and longitude (e.g., 50.83 4.38).
    • -b, --bbox: Bounding box (xmin ymin xmax ymax).
    • -c, --clouds: Maximum cloud cover (1-100).
    • -s, --start: Start date (YYYY-MM-DD).
    • -e, --end: End date (YYYY-MM-DD).
    • -o, --output: Output format (entity_id, display_id, json, or csv).
    • -m, --limit: Maximum number of results.
    # Search for Landsat 5 TM scenes at a specific location and year
    landsatxplore search --dataset landsat_tm_c2_l1 --location 12.53 -1.53 \
        --start 1995-01-01 --end 1995-12-31
    
    # Search for Landsat 7 ETM scenes in Brussels with <5% clouds and save to CSV
    landsatxplore search --dataset landsat_etm_c2_l2 \
        --location 50.83 4.38 --clouds 5 > results.csv
  10. Download Landsat scenes via CLI

    master

    Use the landsatxplore download command to download one or more scenes. If the --dataset is not provided, the package attempts to guess it from the scene identifier. For Landsat Collection 2 products, it is recommended to set the --dataset option explicitly.

    Options:

    • -d, --dataset: The dataset ID.
    • -o, --output: The output directory path.
    • -t, --timeout: Download timeout in seconds.
    • --skip: Skip existing files.
    • [SCENES]...: One or more scene identifiers.
    # Download specific scenes to the current directory
    landsatxplore download LT51960471995178MPS00 LC80390222013076EDC00 LC82150682015350LGN01
  11. Convert strings to snake_case

    master

    Two utility functions are provided for string transformation:

    1. title_to_snake(src_string): Converts a title string to snake_case. It replaces spaces with underscores and forward slashes / with hyphens -.
    2. camel_to_snake(src_string): Converts a camelCase string to snake_case by inserting underscores before uppercase letters and converting the entire string to lowercase.
    from landsatxplore.util import title_to_snake, camel_to_snake
    
    print(title_to_snake("My Title/String"))  # 'my_title-string'
    print(camel_to_snake("myCamelCaseString")) # 'my_camel_case_string'