### Example INI Configuration File Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/configuration.md This is an example of an INI-style configuration file, demonstrating the use of sections and comments for general and connection settings. ```ini [General] # Print loaded configuration file and default back-end URLs in interactive mode verbose = auto [Connection] default_backend = openeo.cloud ``` -------------------------------- ### Install OpenEO Python Client Source: https://github.com/open-eo/openeo-python-client/wiki/Guided-usage-exercise Install the openEO Python client package using pip. This is the first step before importing it into your Python environment. ```bash pip install openeo ``` -------------------------------- ### Install openEO with local processing support Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/localprocessing.md Install the openEO Python client with the necessary dependencies for local processing. This command ensures all required packages are included. ```bash pip install openeo[localprocessing] ``` -------------------------------- ### Install openEO with Jupyter Dependencies Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/installation.md Install the openEO Python client along with extra dependencies required for on-demand preview and other Jupyter-enabled features. ```bash pip install openeo[jupyter] ``` -------------------------------- ### Example Process in JSON Notation Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/processes.md Illustrates the JSON structure for a simple 'add' process with its arguments. ```default { "process_id": "add", "arguments": {"x": 3, "y": 5} } ``` -------------------------------- ### Execute DataCube from Process Example Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/datacube_construction.md Demonstrates executing a DataCube constructed from a 'mean' process, showing a simple calculation. ```default cube = connection.datacube_from_process("mean", data=[2, 3, 5, 8]) cube.execute() ``` -------------------------------- ### Install openeo with artifact support Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/api-artifacts.md Install the openeo Python client with the necessary extra packages for artifact functionality. This command ensures all dependencies for handling artifacts are included. ```shell pip install "openeo[artifacts]" --upgrade ``` -------------------------------- ### Verify openEO Python Client Installation Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/installation.md Import the openeo package and print its version to confirm a successful installation. This can be done in a Python script, interactive shell, or notebook. ```python import openeo print(openeo.client_version()) ``` -------------------------------- ### Install openEO Python Client from Source in Development Mode Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/installation.md Install the package in development mode from a git source checkout. This allows for direct modification of the source code without re-installation. Includes development-related dependencies. ```bash pip install -e .[dev] ``` -------------------------------- ### Serve Documentation Locally with Python HTTP Server Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Starts a local HTTP server from the 'docs' folder to host the built HTML documentation. Visit http://127.0.0.1:8000/_build/html/ in your browser. ```shell # From `docs` folder python -m http.server 8000 ``` -------------------------------- ### Install openEO Python Client with Conda Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/installation.md Install the openEO Python client library within a conda environment using the conda-forge channel. ```bash conda install -c conda-forge openeo ``` -------------------------------- ### Verify PyPI Release with Docker Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Installs the openeo package in a temporary Docker container and verifies the installation by printing the package and its version. This is a quick way to test the release on PyPI. ```bash docker run --rm -it python python -m pip install --no-deps openeo ``` -------------------------------- ### Start a Batch Job Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/batch_jobs.md Initiate the processing of a created batch job. ```python job.start() ``` -------------------------------- ### Install openEO Dependencies via Conda Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md After activating the development environment, install only the dependencies required by the 'openeo' package from the conda-forge channel. This step ensures all necessary libraries are present before installing the client in editable mode. ```console # Install openeo dependencies (from the conda-forge channel) conda install --only-deps -c conda-forge openeo ``` -------------------------------- ### Execute Training as Batch Job Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/machine_learning.md Creates and starts a batch job to execute the model training process. Waits for the job to complete. ```python training_job = model.create_job() training_job.start_and_wait() ``` -------------------------------- ### Execute UDF Locally with Downloaded Data Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udf.md This example demonstrates how to execute a UDF locally using `execute_local_udf`. It involves downloading data first (e.g., in NetCDF format) and then running the UDF on the downloaded file. This is primarily for client-side development with small datasets. ```python from pathlib import Path from openeo.udf import execute_local_udf my_process = connection.load_collection(...) my_process.download('test_input.nc', format='NetCDF') smoothing_udf = Path('smooth_savitzky_golay.py').read_text() execute_local_udf(smoothing_udf, 'test_input.nc', fmt='netcdf') ``` -------------------------------- ### Start and Wait for an Existing Batch Job Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/batch_jobs.md Starts an existing batch job and polls its status until it finishes or fails. Progress messages are printed during execution. This is useful when you have a `BatchJob` instance already created. ```python >>> job.start_and_wait() 0:00:00 Job 'b0e8adcf-087f-41de-afe6-b3c0ea88ff38': send 'start' 0:00:36 Job 'b0e8adcf-087f-41de-afe6-b3c0ea88ff38': queued (progress N/A) 0:01:35 Job 'b0e8adcf-087f-41de-afe6-b3c0ea88ff38': queued (progress N/A) 0:02:19 Job 'b0e8adcf-087f-41de-afe6-b3c0ea88ff38': running (progress N/A) 0:02:50 Job 'b0e8adcf-087f-41de-afe6-b3c0ea88ff38': running (progress N/A) 0:03:28 Job 'b0e8adcf-087f-41de-afe6-b3c0ea88ff38': finished (progress N/A) ``` -------------------------------- ### Upgrade openEO Python Client with pip Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/installation.md Run this command to upgrade an existing installation of the openEO Python client library to the latest release. ```bash pip install --upgrade openeo ``` -------------------------------- ### Load Collection into DataCube Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/datacube_construction.md The primary method to start building a DataCube is by loading a collection using `connection.load_collection()`. This is suitable for most common use cases. ```default cube = connection.load_collection("SENTINEL2_TOC") ``` -------------------------------- ### Install Pre-commit Git Hook Scripts Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Installs the project-specific git hook scripts for pre-commit checks. This helps ensure basic code style and quality in contributions. ```shell pre-commit install ``` -------------------------------- ### Connect, Load, Process, and Download Data Source: https://github.com/open-eo/openeo-python-client/blob/master/README.md This snippet demonstrates how to connect to an openEO backend, load a specific collection, apply processing steps like rescaling and temporal maximum, and download the result as a TIFF file. Ensure you have the 'openeo' package installed. ```python import openeo # Connect to openEO back-end. connection = openeo.connect("openeo.vito.be").authenticate_oidc() # Load data cube from TERRASCOPE_S2_NDVI_V2 collection. cube = connection.load_collection( "TERRASCOPE_S2_NDVI_V2", spatial_extent={"west": 5.05, "south": 51.21, "east": 5.1, "north": 51.23}, temporal_extent=["2022-05-01", "2022-05-30"], bands=["NDVI_10M"], ) # Rescale digital number to physical values and take temporal maximum. cube = cube.apply(lambda x: 0.004 * x - 0.08).max_time() cube.download("ndvi-max.tiff") ``` -------------------------------- ### Verify PyPI Release with Temporary Virtual Environment Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md A bash one-liner to verify the PyPI release by installing the openeo package in a temporary virtual environment, importing it, and printing its version. This script automates the verification process. ```bash ( cd /tmp && python -m venv venv-openeo && source venv-openeo/bin/activate && pip install -U openeo && python -c "import openeo;print(openeo);print(openeo.__version__)" ) ``` -------------------------------- ### Import OpenEO Python Client Source: https://github.com/open-eo/openeo-python-client/wiki/Guided-usage-exercise Import the openEO library into your Python script or Jupyter notebook after installation. ```python import openeo ``` -------------------------------- ### Invoking a User-Defined Process Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udp.md Example of how to invoke the 'fahrenheit_to_celsius' user-defined process with a specific input value for the 'fahrenheit' parameter. ```json { "process_id": "fahrenheit_to_celsius", "arguments": {"fahrenheit": 70} } ``` -------------------------------- ### Sample Feature Collection for Training Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/machine_learning.md Example GeoJSON FeatureCollection with sample points and target values for training a classification model. Ensure to replace '...' with actual data. ```json { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {"id": "b3dw-wd23", "target": 3}, "geometry": {"type": "Point", "coordinates": [3.4, 51.1]} }, { "type": "Feature", "properties": {"id": "r8dh-3jkd", "target": 5}, "geometry": {"type": "Point", "coordinates": [3.6, 51.2]} }, ... } } ``` -------------------------------- ### Declare Advanced Python UDF Dependencies Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udf.md An advanced example demonstrating PEP 723 dependency declaration, including version constraints, package URLs, and comments. It illustrates more complex dependency specifications. ```python # /// script # dependencies = [ # # A comment about using at least version 2.5.0 # 'geojson>=2.5.0', # An inline comment # # Note that TOML allows both single and double quotes for strings. # # # Install a package "fancyeo" from a (ZIP) source archive URL. # "fancyeo @ https://github.com/fncy/fancyeo/archive/refs/tags/v3.2.0-alpha1.zip", # # Or from a wheel URL, including a content hash to be verified before installing. # "lousyeo @ https://example.com/lousyeo-6.6.6-py3-none-any.whl#sha1=4bbb3c72a9234ee998a6de940a148e346a", # # Note that the last entry may have a trailing comma. # ] # /// ``` -------------------------------- ### Compute Spectral Indices with Manual Platform Specification Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/spectral_indices.md Compute spectral indices when the platform needs to be explicitly specified due to missing metadata. This guides the band mapping process. ```python indices = compute_indices( cube, indices=["NDVI", "NDMI"], platform="SENTINEL2", ) ``` -------------------------------- ### Run Unit Tests with Pytest Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Executes the entire test suite for the openEO Python Client using the pytest framework. Ensure you have installed the project with the '[dev]' extra. ```shell pytest ``` -------------------------------- ### Calling a Public UDP via URL Namespace Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/udp_sharing.md Uses a public user-defined process by specifying its public URL as the 'namespace' in a process graph node. This example demonstrates calling the process and executing the graph. ```default cube = connection.datacube_from_process( process_id="fahrenheit_to_celsius", namespace="https://openeo.vito.be/openeo/1.0/processes/u:johndoe/fahrenheit_to_celsius", f=86 ) print(cube.execute()) # Prints: 30.0 ``` -------------------------------- ### Declare Basic Python UDF Dependencies Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udf.md A basic example of declaring UDF dependencies using the PEP 723 standard within a top-level comment block. This is the preferred approach if supported by the backend. ```python # /// script # dependencies = [ # "geojson", # "fancy-eo-library", # ] # /// # # This openEO UDF script implements ... # based on the fancy-eo-library ... using geosjon data ... import geojson import fancyeo def apply_datacube(cube: xarray.DataArray, context: dict) -> xarray.DataArray: ... ``` -------------------------------- ### UDF with Metadata Transformation Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udf.md This example shows a UDF that includes an `apply_metadata` function to modify cube metadata, specifically by resampling spatial dimensions. It also includes `fancy_upsample_function` and `apply_datacube` for data transformation, demonstrating how to handle UDFs that impact metadata. ```python import numpy as np import xarray from openeo.metadata import CollectionMetadata from openeo.udf.debug import inspect def apply_metadata(input_metadata: CollectionMetadata, context: dict) -> CollectionMetadata: res= [ d.step / 2.0 for d in input_metadata.spatial_dimensions] return input_metadata.resample_spatial(resolution=res) def fancy_upsample_function(array: np.array, factor: int = 2) -> np.array: assert array.ndim == 3 return array.repeat(factor, axis=-1).repeat(factor, axis=-2) def apply_datacube(cube: xarray.DataArray, context: dict) -> xarray.DataArray: cubearray: xarray.DataArray = cube.copy() + 60 # We make prediction and transform numpy array back to datacube # Pixel size of the original image init_pixel_size_x = cubearray.coords["x"][-1].item() - cubearray.coords["x"][-2].item() init_pixel_size_y = cubearray.coords["y"][-1].item() - cubearray.coords["y"][-2].item() if cubearray.data.ndim == 4 and cubearray.data.shape[0] == 1: cubearray = cubearray[0] predicted_array = fancy_upsample_function(cubearray.data, 2) inspect(data=predicted_array, message=f"predicted array") coord_x = np.linspace( start=cube.coords["x"].min().item(), stop=cube.coords["x"][-1].item() + init_pixel_size_x, num=predicted_array.shape[-2], endpoint=False, ) coord_y = np.linspace( start=cube.coords["y"].min().item(), stop=cube.coords["y"].max().item() + init_pixel_size_y, num=predicted_array.shape[-1], endpoint=False, ) predicted_cube = xarray.DataArray( predicted_array, dims=["bands", "x", "y"], coords=dict(x=coord_x, y=coord_y), ) return predicted_cube ``` -------------------------------- ### Spectral Index Definition Example Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/spectral_indices.md Example of a spectral index definition in JSON format, showing the formula and long name for NDVI. ```json "NDVI": { "formula": "(N - R)/(N + R)", "long_name": "Normalized Difference Vegetation Index", ``` -------------------------------- ### Build Documentation with Make Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Builds the project documentation in HTML format from the 'docs' folder using the Makefile. Assumes 'make' is available. ```shell # From `docs` folder make html ``` -------------------------------- ### Build Documentation with Sphinx (Makefile alternative) Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Builds the project documentation in HTML format using Sphinx directly. This is an alternative if 'make' is not available. ```shell python -msphinx -M html . _build ``` -------------------------------- ### Connect Using Default Configuration Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/auth.md When default back-end and auto-authentication are configured, you can establish an authenticated connection simply by calling `openeo.connect()`. ```python >>> import openeo >>> connection = openeo.connect() Loaded openEO client config from openeo-client-config.ini Using default back-end URL 'openeo.cloud' (from config) Doing auto-authentication 'oidc' (from config) Authenticated using refresh token. ``` -------------------------------- ### Display `openeo-auth` help message Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/auth.md Shows the available subcommands and options for the `openeo-auth` tool. Use this to understand the tool's capabilities. ```bash $ openeo-auth -h usage: openeo-auth [-h] [--verbose] {paths,config-dump,token-dump,add-basic,add-oidc,oidc-auth} ... Tool to manage openEO related authentication and configuration. optional arguments: -h, --help show this help message and exit Subcommands: {paths,config-dump,token-dump,add-basic,add-oidc,oidc-auth} paths Show paths to config/token files. config-dump Dump config file. ... ``` -------------------------------- ### Upload file using Artifact Helper Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/api-artifacts.md Demonstrates the core workflow for uploading a file as an artifact. Connect to your openEO backend, build an artifact helper, upload the file, and retrieve a presigned URI for access. The presigned URI should be kept secret if the data is sensitive. ```python import openeo from openeo.extra.artifacts import build_artifact_helper connection = openeo.connect("my-openeo.prod.example").authenticate_oidc() artifact_helper = build_artifact_helper(connection) storage_uri = artifact_helper.upload_file(path, object_name) presigned_uri = artifact_helper.get_presigned_url(storage_uri) ``` -------------------------------- ### Show `openeo-auth` config and token file paths Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/auth.md Displays the locations of the authentication configuration and refresh token files. These paths are important for managing your credentials. ```bash $ openeo-auth paths openEO auth config: /home/john/.config/openeo-python-client/auth-config.json (perms: 0o600, size: 1414B) openEO OpenID Connect refresh token store: /home/john/.local/share/openeo-python-client/refresh-tokens.json (perms: 0o600, size: 846B) ``` -------------------------------- ### Build Wheel Archive Locally Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Builds a wheel archive of the openeo package locally. This is an alternative to using GitHub Actions for building release artifacts. ```bash python setup.py bdist_wheel ``` -------------------------------- ### Add Basic HTTP Auth Credentials to Config Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/auth.md Use the `openeo-auth` command-line tool to add Basic HTTP Auth credentials for a specific back-end to the client's configuration file. This allows for automatic authentication later. ```bash $ openeo-auth add-basic https://openeo.example.com/ Enter username and press enter: john Enter password and press enter: Trying to authenticate with 'https://openeo.example.com' Successfully authenticated 'john' Saved credentials to '/home/john/.config/openeo-python-client/auth-config.json' ``` -------------------------------- ### Fahrenheit to Celsius Conversion Formula Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udp.md A simple mathematical formula for converting Fahrenheit to Celsius. This serves as a conceptual example for a parameterized user-defined process. ```default c = (f - 32) / 1.8 ``` -------------------------------- ### Using openeo.processes Functions as Callbacks Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/api-processes.md Demonstrates how to use functions from the openeo.processes module directly as callbacks for DataCube methods. Ensure the callback function signature matches the expected input of the DataCube method. ```python from openeo.processes import absolute, max cube.apply(absolute) cube.reduce_dimension(max, dimension="t") ``` -------------------------------- ### Filter Temporal Data Cube Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/processes.md Applies a temporal filter to a raster data cube using the `filter_temporal` method. Specify start and end dates. ```default cube = cube.filter_temporal("2020-02-20", "2020-06-06") ``` -------------------------------- ### Chained Methods Callback for Reduce Dimension Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/processes.md Defines a callback for reduce_dimension using chained ProcessBuilder methods. This example applies mean, cos, and add operations sequentially. ```python from openeo.processes import ProcessBuilder, mean, cos, add # Chained methods cube.reduce_dimension( lambda data: data.mean().cos().add(y=1.23), dimension="t" ) ``` -------------------------------- ### Apply Standard Process (Absolute) Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/processes.md Applies a standard openEO process, like 'absolute', directly as a callback to a data cube. Ensure the process is imported from 'openeo.processes'. ```python from openeo.processes import absolute cube.apply(absolute) ``` -------------------------------- ### Add OpenID Connect credentials using `openeo-auth` Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/auth.md Interactively adds OpenID Connect client ID and secret to the configuration file for a specified backend. This simplifies subsequent authentication calls. ```bash $ openeo-auth add-oidc https://openeo.example.com/ Using provider ID 'example' (issuer 'https://oidc.example.net/') Enter client_id and press enter: client-d7393fba Enter client_secret and press enter: Saved client information to '/home/john/.config/openeo-python-client/auth-config.json' ``` -------------------------------- ### Dump `openeo-auth` configuration Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/auth.md Outputs the content of the authentication configuration file. Sensitive information like passwords is redacted by default. ```bash $ openeo-auth config-dump ### /home/john/.config/openeo-python-client/auth-config.json ############### { "backends": { "https://openeo.example.com": { "basic": { "username": "john", "password": "", "date": "2020-07-24T13:40:50Z" ... ``` -------------------------------- ### SentinelHub Normalized Radar Backscatter Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/ard.md Example of using SentinelHub's implementation for normalized radar backscatter. This method is CARD4L compliant and supports various processing options. ```python s1grd = (connection.load_collection('SENTINEL1_GRD', bands=['VH', 'VV']) .filter_bbox(west=2.59003, east=2.8949, north=51.2206, south=51.069) .filter_temporal(extent=["2019-10-10","2019-10-10"])) job = s1grd.ard_normalized_radar_backscatter().execute_batch() for asset in job.get_results().get_assets(): asset.download() ``` -------------------------------- ### Initiate OIDC Device Code Flow Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/auth.md Use this function to start the interactive device code flow for OIDC authentication. A web browser is required for the user to complete the authentication. ```python connection.authenticate_oidc_device() ``` -------------------------------- ### Create a job database from a CSV file Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/job_manager.md Initializes a job database using a local CSV file. This allows for persistence and resumption of job processing. ```python from openeo.extra.job_management import create_job_db job_db = create_job_db("jobs.csv", df=df) ``` -------------------------------- ### Chained ProcessBuilder Methods for Callback Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/processes.md Defines a callback using chained ProcessBuilder methods for a compact, readable process graph definition. This example chains 'absolute', 'cos', and 'add' operations. ```python cube.apply( lambda x: x.absolute().cos().add(y=1.23) ) ``` -------------------------------- ### Construct DataCube from Local File or URL Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/datacube_construction.md Load a DataCube directly from a local JSON file or a URL pointing to a JSON representation of an openEO process graph. This is convenient for reusing predefined process definitions. ```python # Local file cube = connection.datacube_from_json("path/to/my_udp.json") ``` ```python # URL cube = connection.datacube_from_json("https://example.com/my_udp.json") ``` -------------------------------- ### Load and Prepare Predictor Bands Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/machine_learning.md Loads Sentinel-2 collection, extracts specified bands, and reduces the temporal dimension by taking the mean. Requires 'connection', 'start', 'end', and 'bbox' to be defined. ```python cube = connection.load_collection( "SENTINEL2", temporal_extent=[start, end], spatial_extent=bbox, bands=["B02", "B03", "B04"] ) cube = cube.reduce_dimension(dimension="t", reducer="mean") ``` -------------------------------- ### Build and Live-Reload Documentation with Sphinx-Autobuild Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Uses sphinx-autobuild to automatically rebuild documentation on changes and live-reload the browser. Run from the project root. ```shell # From project root sphinx-autobuild docs/ --watch openeo/ docs/_build/html/ ``` -------------------------------- ### Define a start_job callback function Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/job_manager.md This function is called for each row in the job database to create a batch job. It defines the data loading, processing (NDVI calculation), and job creation parameters. ```python def start_job(row, connection, **kwargs): cube = connection.load_collection( "SENTINEL2_L2A", spatial_extent=row["spatial_extent"], temporal_extent=[f"{row['year']}-01-01", f"{row['year']+1}-01-01"], bands=["B04", "B08"], ) cube = cube.ndvi(nir="B08", red="B04") return cube.create_job( title=f"NDVI {row['year']}", out_format="GTiff", ) ``` -------------------------------- ### Filter by Temporal Extent (Date Strings) Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/data_access.md Load a collection within a specified date range using string representations for dates. This uses left-closed intervals (start included, end excluded). ```python connection.load_collection( ..., temporal_extent=["2021-05-07", "2021-05-14"], ) ``` -------------------------------- ### Add and Authenticate a Backend Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/job_manager.md Initializes a MultiBackendJobManager and registers a backend with its connection details. Supports OIDC authentication for secure access. ```python import openeo from openeo.extra.job_management import MultiBackendJobManager manager = MultiBackendJobManager() manager.add_backend("cdse", connection=openeo.connect( "https://openeo.dataspace.copernicus.eu/" ).authenticate_oidc()) ``` -------------------------------- ### Construct DataCube from UDP and Download Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udp.md Constructs a DataCube object from a UDP using datacube_from_process(), applies temporal filtering, and downloads the result. Assumes a UDP named 'fancy_load_collection' exists. ```python cube = connection.datacube_from_process("fancy_load_collection") cube = cube.filter_temporal("2020-09-01", "2020-09-10") cube.download("fancy.tiff", format="GTiff") ``` -------------------------------- ### Evaluate UDP with Custom Process Graph Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udp.md Evaluates a user-defined process by creating a process graph using the generic openeo.processes.process() function and executing it. Shows how to pass arguments to the UDP. ```python pg = openeo.processes.process("fahrenheit_to_celsius", f=70) pg.print_json(indent=None) res = connection.execute(pg) print(res) ``` -------------------------------- ### Filter Temporal with Month Shorthand Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/data_access.md Filter a cube for a specific month using shorthand notation. This is equivalent to specifying the first day of the month as the start date and the first day of the next month as the end date. ```python # Filter for March, April and May (left-closed interval) cube = cube.filter_temporal("2021-03", "2021-06") cube = cube.filter_temporal(["2021-03", "2021-06"]) cube = cube.filter_temporal(start_date="2021-03", end_date="2021-06") cube = cube.filter_temporal(extent=("2021-03", "2021-06")) # The above are shorthand for: cube = cube.filter_temporal("2021-03-01", "2022-06-01") ``` -------------------------------- ### Run batch jobs with a start_job callback Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/job_manager.md Initiates the job processing loop by calling run_jobs with the job database and the start_job callback. Logging is recommended for monitoring progress. ```python import logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO, ) manager.run_jobs(job_db=job_db, start_job=start_job) ``` -------------------------------- ### Filter Temporal with Year Shorthand Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/data_access.md Filter a cube for a specific year using shorthand notation. This is equivalent to specifying the first day of the year as the start date and the first day of the next year as the end date. ```python # Filter for observations in 2021 (left-closed interval). connection.load_collection(temporal_extent=["2021", "2022"], ...) # The above is shorthand for: connection.load_collection(temporal_extent=["2021-01-01", "2022-01-01"], ...) ``` -------------------------------- ### Execute Batch Job from DataCube Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/batch_jobs.md Creates, starts, and waits for a batch job directly from a `DataCube` instance. This method returns a `BatchJob` instance for the newly created job. Useful when the batch job has not been created yet. ```python >>> job = cube.execute_batch() 0:00:00 Job 'f9f4e3d3-bc13-441b-b76a-b7bfd3b59669': send 'start' 0:00:23 Job 'f9f4e3d3-bc13-441b-b76a-b7bfd3b59669': queued (progress N/A) ... ``` -------------------------------- ### Print Load Collection Process Graph JSON Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udp.md Inspects the openEO-style process graph representation of the parameterized cube, showing how the spatial extent is linked to the 'bbox' parameter. ```python cube.print_json() ``` -------------------------------- ### Correct Usage: Using openeo.processes.sum Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/processes.md Shows the correct way to use an openEO process function, 'openeo.processes.sum', as a reducer for dimension reduction. This avoids the runtime errors associated with using builtins. ```python >>> # Explicit usage of `openeo.processes.sum` >>> import openeo.processes >>> cube.reduce_dimension(dimension="t", reducer=openeo.processes.sum) ``` -------------------------------- ### Get Batch Job Results Handle Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/batch_jobs.md Retrieves a handle to the results of a finished batch job. This handle provides access to result metadata and the actual files. The metadata is a STAC item describing the spatio-temporal properties of the result. ```python >>> results = job.get_results() >>> results ``` -------------------------------- ### Create a job database from a Parquet file Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/job_manager.md Initializes a job database using a local Parquet file. This is an alternative to CSV for persisting and resuming job processing. ```python from openeo.extra.job_management import create_job_db job_db = create_job_db("jobs.parquet", df=df) ``` -------------------------------- ### Loading a Published UDP as DataCube from URL Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/udp_sharing.md Constructs a DataCube client-side from a public user-defined process URL. This 'unrolls' the UDP's process graph and requires providing its parameters. ```python udp_url = "https://openeo.vito.be/openeo/1.0/processes/u:johndoe/fahrenheit_to_celsius" cube = connection.datacube_from_json( udp_url, parameters={"f": 86}, ) print(cube.execute()) # Prints: 30.0 ``` -------------------------------- ### OIDC Device Code Flow - User Instructions Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/auth.md Example of the message displayed to the user during the OIDC device code flow, instructing them to visit a URL and enter a user code. This message may include the user code directly in the URL. ```text Visit https://oidc.example.net/device and enter user code 'DTNY-KLNX' to authenticate. ``` ```text Visit https://oidc.example.net/device?user_code=DTNY-KLNX to authenticate. ``` -------------------------------- ### Reduce Dimension with Standard Process (Max) Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/processes.md Applies a standard openEO process, like 'max', as a reducer for dimension reduction. Ensure the process is imported from 'openeo.processes'. ```python from openeo.processes import max cube.reduce_dimension(reducer=max, dimension="t") ``` -------------------------------- ### Apply UDF for Data Scaling Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udf.md This snippet demonstrates how to create an `openeo.UDF` object from inline Python code and apply it to a data cube using the `apply` process. The UDF rescales the band values of the data cube. Download the processed data to inspect the results. ```python import openeo # Create connection to openEO back-end connection = openeo.connect("...").authenticate_oidc() # Load initial data cube. s2_cube = connection.load_collection( "SENTINEL2_L2A", spatial_extent={"west": 4.00, "south": 51.04, "east": 4.10, "north": 51.1}, temporal_extent=["2022-03-01", "2022-03-31"], bands=["B02", "B03", "B04"], ) # Create a UDF object from inline source code. udf = openeo.UDF( """ import xarray def apply_datacube(cube: xarray.DataArray, context: dict) -> xarray.DataArray: cube.values = 0.0001 * cube.values return cube """ ) # Pass UDF object as child process to `apply`. rescaled = s2_cube.apply(process=udf) rescaled.download("apply-udf-scaling.nc") ``` -------------------------------- ### Load JSON Asset Directly Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/batch_jobs.md Load a JSON asset directly into memory using `load_json()` without saving it to disk. This is useful for inspecting or processing JSON results immediately. The example shows accessing asset metadata and then loading the JSON content. ```python >>> asset.metadata {"type": "application/json", "href": "https://openeo.example/download/432f3b3ef3a.json"} >>> data = asset.load_json() >>> data {"2021-02-24T10:59:23Z": [[3, 2, 5], [3, 4, 5]], .... ``` -------------------------------- ### Configure Default Back-end and Auto-Authentication Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/auth.md Define a default back-end URL and authentication method (e.g., 'oidc') in a client configuration file for convenience. This is separate from authentication-specific config files. ```ini [Connection] default_backend = openeo.cloud default_backend.auto_authenticate = oidc ``` -------------------------------- ### Get Batch Job Result Metadata Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/batch_jobs.md Retrieves the metadata for a batch job's results. This metadata is a valid STAC item and includes information such as bounding box, geometry, and a list of assets (result files) with their properties like `href` and `type`. ```python >>> results.get_metadata() { 'bbox': [3.5, 51.0, 3.6, 51.1], 'geometry': {'coordinates': [[[3.5, 51.0], [3.5, 51.1], [3.6, 51.1], [3.6, 51.0], [3.5, 51.0]]], 'type': 'Polygon'}, 'assets': { 'res001.tiff': { 'href': 'https://openeo.example/download/432f3b3ef3a.tiff', 'type': 'image/tiff; application=geotiff', ... }, 'res002.tiff': { ... } } } ``` -------------------------------- ### Construct DataCube from Raw JSON String (Process Graph with Parameters) Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/datacube_construction.md Load a DataCube from a raw JSON string that includes both 'parameters' and a 'process_graph'. This allows for dynamic DataCube construction with configurable inputs. ```python raw_json = '''{ "parameters": [ {"name": "kernel", "schema": {"type": "array"}, "default": [[1,2,1], [2,5,2], [1,2,1]]} ], "process_graph": { "lc": {"process_id": "load_collection", "arguments": {"id": "SENTINEL2_TOC"}}, "ak": {"process_id": "apply_kernel", "arguments": {"data": {"from_node": "lc"}, "kernel": {"from_parameter": "kernel"}}, "result": true} } }''' cube = connection.datacube_from_json(raw_json) ``` -------------------------------- ### Create and Activate Conda Environment Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Use these commands to create and activate a new conda environment specifically for developing the openeo-python-client. This isolates project dependencies. ```console conda create -n openeopyclient conda activate openeopyclient ``` -------------------------------- ### Download Process Graph from Local JSON File Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/tricks.md Download data by executing a process graph defined in a local JSON file. The `Connection.download()` method accepts a file path directly. ```python # `download` with local path to JSON file connection.download("path/to/my-process-graph.json") ``` -------------------------------- ### Create and Persist Job Database Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/job_manager.md Prepares a job database using a pandas DataFrame and wraps it in a persistent storage format (CSV). This database describes individual jobs, and the manager automatically adds bookkeeping columns. ```python import pandas as pd from openeo.extra.job_management import create_job_db df = pd.DataFrame({ "spatial_extent": [ {"west": 5.0, "south": 51.0, "east": 5.1, "north": 51.1}, {"west": 5.1, "south": 51.1, "east": 5.2, "north": 51.2}, ], "year": [2021, 2022], }) job_db = create_job_db("jobs.csv", df=df) ``` -------------------------------- ### List Available UDF Runtimes and Libraries Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udf.md Inspect available libraries for a specific UDF runtime, such as 'Python' version '3'. This helps in understanding pre-installed packages. ```python >>> connection.list_udf_runtimes()["Python"]["versions"]["3"]["libraries"] {'geopandas': {'version': '0.13.2'}, 'numpy': {'version': '1.22.4'}, 'xarray': {'version': '0.16.2'}, ... } ``` -------------------------------- ### Apply PGNode for Custom Operations Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/processes.md Demonstrates how to use PGNode to define custom operations like 'add' and 'cos' within an apply process. This is useful for complex, non-standard processing chains. ```python from openeo.internal.graph_building import PGNode cube.apply(PGNode( "add", x=PGNode( "cos", x=PGNode("absolute", x={"from_parameter": "x"}) ), y=1.23 )) ``` -------------------------------- ### Using a Custom Tile Grid for Splitting Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/cookbook/job_manager.md Load a pre-computed tile grid from a file (e.g., GeoParquet) and use it with `split_area` to obtain only tiles that intersect the area of interest. This ensures pixel-aligned tile boundaries. ```python import geopandas as gpd from openeo.extra.job_management import split_area extent = {"west": 5.0, "south": 51.0, "east": 5.2, "north": 51.2, "crs": "EPSG:4326"} # Load a pre-computed tile grid (e.g. a pixel-aligned UTM grid stored as GeoParquet) tile_grid = gpd.read_parquet("my_tile_grid.parquet") # Only tiles intersecting the AOI are returned gdf = split_area(aoi=extent , tile_grid=tile_grid) ``` -------------------------------- ### Connect to openEO Back-end Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/basics.md Establish a connection to an openEO back-end using its URL. This object is used for all subsequent interactions with the back-end. ```python import openeo connection = openeo.connect("openeo.vito.be") ``` -------------------------------- ### Create Git Tag and Push Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/development.md Creates a Git tag for the release and pushes it to the remote repository. This is a crucial step for version control and release management. ```bash git tag v0.8.0 git push origin v0.8.0 ``` -------------------------------- ### Complex Reducer with ProcessBuilder Methods and Functions Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/api-processbuilder.md Demonstrates mixing ProcessBuilder methods, openEO process functions (like 'cos'), and arithmetic operators within a reducer function. The result is a new ProcessBuilder instance representing the composed operations. ```python from openeo.processes import ProcessBuilder, cos def my_reducer(data: ProcessBuilder) -> ProcessBuilder: return cos(data.mean()) + 1.23 cube.reduce_dimension(reducer=my_reducer, dimension="t") ``` -------------------------------- ### Legacy vs. New UDF Usage with apply_dimension Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udf.md Demonstrates the deprecated legacy usage of `apply_dimension` with explicit `code` and `runtime` arguments, and contrasts it with the new, preferred approach using a `openeo.UDF` object passed to the standard `process` argument. The legacy method will trigger a deprecation warning. ```python udf_code = """ ... def apply_datacube(cube, ... """ # Legacy `apply_dimension` usage: still works for now, # but it will trigger a deprecation warning. cube.apply_dimension(code=udf_code, runtime="Python", dimension="t") # New, preferred approach with a standard `process` argument. udf = openeo.UDF(udf_code) cube.apply_dimension(process=udf, dimension="t") # Unchanged: usage of other apply/reduce/... methods cube.apply(process=udf) cube.reduce_dimension(reducer=udf, dimension="t") ``` -------------------------------- ### Access Federated Backend Details Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/federation-extension.md Retrieve and print details about participating backends in a federation from the capabilities document. Requires an established connection to an openEO service. ```python import openeo connection = openeo.connect(url=...) capabilities = connection.capabilities() print("Federated backends:", capabilities.ext_federation_backend_details()) ``` -------------------------------- ### Define Fahrenheit to Celsius Conversion Process Source: https://github.com/open-eo/openeo-python-client/blob/master/docs/udp.md Builds a process graph for Fahrenheit to Celsius conversion using symbolic process functions and saves it as a user-defined process. Requires importing subtract, divide, and Parameter. ```python from openeo.processes import subtract, divide from openeo.api.process import Parameter # Define the input parameter. f = Parameter.number("f", description="Degrees Fahrenheit.") # Do the calculations, using the parameter and other values fahrenheit_to_celsius = divide(x=subtract(x=f, y=32), y=1.8) # Store user-defined process in openEO back-end. connection.save_user_defined_process( "fahrenheit_to_celsius", fahrenheit_to_celsius, parameters=[f] ) ```