Alternative - in-memory results, a pinned grid, and the pixel API¶
download() returns the written paths. materialize=True returns a DownloadResult that still is that
list for every existing caller, but also carries the in-memory pyramids objects, so the next operation
needs no re-read. The cells below are commented out because they fetch pixels; uncomment one after
authenticate(...) has run.
# result = el.download(materialize=True)
#
# result.paths # the written GeoTIFFs, exactly what download() returned before
# result.objects # the in-memory pyramids Datasets
# result.objects[0].slope() # straight into a pyramids operation, no re-read
# cube = result.collection() # or stack the buckets into a DatasetCollection
#
# with el.download(materialize=True) as result: # closes the datasets for you
# print(result.objects[0].stats())
#
# A pinned output grid - pixel size *and* origin - so stacked dates align without a
# resample, fetched through `ee.data.computePixels`, which evaluates the composite
# server-side. Earth Engine caps that request at 32768 px per axis as well,
# so an oversize AOI needs auto_split=True there too:
#
# el = EarthLens(
# data_source='gee',
# start='2020-06-01', end='2020-08-31', temporal_resolution='monthly',
# variables={'UCSB-CHG/CHIRPS/DAILY': ['precipitation']},
# lat_lim=[28.0, 32.0], lon_lim=[30.0, 34.0],
# path='out/quickstart', scale=5566,
# engine='pixels',
# crs_transform=(0.05, 0.0, 30.0, 0.0, -0.05, 32.0),
# nodata=-9999,
# )
Quick start — Earth Engine via the EarthLens facade¶
This notebook is the script-form quickstart for the GEE backend. The per-category
notebooks in this directory each use earthlens.gee.GEE(...) directly; this one
demonstrates the unified EarthLens facade entry point — the same call
pattern that works for the CHC, S3, and ECMWF backends.
It also shows the two most common follow-on patterns as commented blocks:
- bypassing the facade with
GEE(...)directly; - queueing an asynchronous Drive export for an AOI too large for the synchronous URL path.
The notebook reads service-account credentials from GEE_SERVICE_ACCOUNT and
GEE_SERVICE_KEY environment variables. See
Service account setup for the
one-time provisioning steps.
Setup¶
Imports and credentials up front. earthlens provides the unified EarthLens entry
point; earthlens.gee.Catalog is the offline band/metadata catalog. Service-account
credentials are read from GEE_SERVICE_ACCOUNT / GEE_SERVICE_KEY (with placeholder
fallbacks so the catalog cells below still run without them).
import os
from earthlens.core import EarthLens
from earthlens.gee import Catalog
SERVICE_ACCOUNT = os.environ.get(
'GEE_SERVICE_ACCOUNT', 'my-sa@my-project.iam.gserviceaccount.com'
)
SERVICE_KEY = os.environ.get('GEE_SERVICE_KEY', '/path/to/key.json')
Browse the catalog (no network, no auth)¶
The catalog ships with the package and parses ~57 k lines of curated YAML in ~3 s cold / ~1 ms warm. Use it to discover what's available and look up a band's units before issuing a download.
catalog = Catalog()
print(
f'{len(catalog.datasets)} curated datasets; '
f'{len(catalog.available_datasets)} in the Earth Engine STAC index'
)
chirps = catalog.get_dataset('UCSB-CHG/CHIRPS/DAILY')
print(chirps)
print(f' ee_type={chirps.ee_type}, cadence={chirps.cadence}')
print(f' bands: {list(chirps.bands)}')
print(
f" precipitation units: {catalog.get_band('UCSB-CHG/CHIRPS/DAILY', 'precipitation').units}"
)
The object API (no network, no auth)¶
Every knob is a string, and every string still works. Behind them the backend resolves each one to an
object, which you can also pass directly when you want something no string expresses - a 90th-percentile
composite, say. The same applies to the output grid: OutputGrid is where an AOI, a CRS and a scale
become a pixel count, with one named constructor per convention.
from earthlens.gee import (
OutputGrid,
Percentile,
resolve_engine,
resolve_reducer,
resolve_sink,
)
# A name, a parameterised spec, and an instance all resolve to the same kind of object.
print(resolve_reducer('median'), resolve_reducer('percentile:90'), Percentile(q=90))
print(resolve_engine('auto'), resolve_engine('pixels'))
print('drive needs:', resolve_sink('drive').required_config)
# The two sizing conventions, which genuinely disagree away from the equator:
# Earth Engine reads `scale` in a geographic CRS as a uniform degree-equivalent,
# while the EEDAI reader sizes for square metres on the ground.
bbox = (31.2, 29.9, 31.3, 30.0)
CRS = 'EPSG:4326'
print(
'earth engine:',
OutputGrid.for_earth_engine(bbox, crs=CRS, scale=90.0).as_rows_cols(),
)
print(
'metre grid: ',
OutputGrid.for_metre_grid(bbox, crs=CRS, scale=90.0).as_rows_cols(),
)
# Or pin the grid outright, so two downloads over different AOIs share pixel edges.
pinned = OutputGrid.from_crs_transform(
bbox, crs=CRS, crs_transform=(0.001, 0.0, 31.2, 0.0, -0.001, 30.0)
)
print('pinned: ', pinned.convention, pinned.as_rows_cols(), pinned.crs_transform)
Download via the EarthLens facade¶
Monthly CHIRPS precipitation composites over a small bbox in Egypt for
Jun-Aug 2020. EarthLens(...) resolves data_source="gee" to the GEE
backend via its _LazyRegistry; the remaining kwargs forward verbatim to
GEE(...). Output is one GeoTIFF per month (three files total) under
out/quickstart/.
Build the request¶
EarthLens(...) resolves data_source="gee" to the GEE backend via its
_LazyRegistry; the remaining kwargs forward verbatim to GEE(...). Keeping the
constructor on its own statement makes the request easy to read and re-run.
el = EarthLens(
data_source='gee',
start='2020-06-01',
end='2020-08-31',
cadence='monthly',
dataset='UCSB-CHG/CHIRPS/DAILY',
variables=['precipitation'],
aoi=[30.0, 28.0, 34.0, 32.0],
path='out/quickstart',
scale=5566,
)
Authenticate¶
authenticate() resolves the service-account credentials and initialises Earth Engine.
It is kept as its own step so the request build and the network handshake stay separate.
el.authenticate(
service_account=SERVICE_ACCOUNT,
service_key=SERVICE_KEY,
)
Download¶
download() writes one GeoTIFF per month (three files total) under out/quickstart/
and returns the list of written paths.
paths = el.download(progress_bar=False)
for p in paths:
print(p)
Alternative — bypass the facade with GEE(...)¶
The per-category notebooks in this directory all use this form. It's a thinner call (no registry lookup) and gives the IDE precise type hints for the backend's kwargs.
# Equivalent to the cell above:
#
# from earthlens.gee import GEE
# gee = GEE(
# start='2020-06-01', end='2020-08-31', temporal_resolution='monthly',
# variables={'UCSB-CHG/CHIRPS/DAILY': ['precipitation']},
# lat_lim=[28.0, 32.0], lon_lim=[30.0, 34.0],
# path='out/quickstart', scale=5566,
# service_account=SERVICE_ACCOUNT, service_key=SERVICE_KEY,
# )
# gee.download(progress_bar=False)
Alternative — asynchronous Drive export for large AOIs¶
The default export_via="url" uses getDownloadURL which is capped at
32768 px per axis. For larger AOIs queue an
ee.batch.Export.image.toDrive task instead; download() will block while
it runs and surface the destination string when it's done.
For non-blocking submission see track-batch-exports.ipynb and the
per-category notebooks' "Tracking submitted jobs" sections — pass
wait_for_export=False and call wait_for_task_id(...) later.
# el = EarthLens(
# data_source='gee',
# start='2023-01-01', end='2023-12-31', temporal_resolution='monthly',
# variables={'COPERNICUS/S2_SR_HARMONIZED': ['B4', 'B8']},
# lat_lim=[51.0, 53.0], lon_lim=[4.0, 7.0],
# scale=10, export_via='drive', drive_folder='ee_exports',
# service_account=SERVICE_ACCOUNT, service_key=SERVICE_KEY,
# )
# locations = el.download()