A unified toolkit for retrieving climate data from various global datasets such as CHIRPS, ERA5-Land, TerraClimate, IMERG, TAMSAT, CHIRTS-ERA5, ERA5, NEX-GDDP, NASA POWER, CMIP6 and SoilGrids.
— what the toolkit is, who it's for, and how to get involved (also in français / español).
— full documentation: getting started, workflows, and API reference.
— published on PyPI:
pip install climate-toolkit.
Email Pete to subscribe for a short note with each stable release, including changes that may affect your code or results. Reply “unsubscribe” to leave.
— try the toolkit live in your browser, no install needed.
— ERA LTE workflow: validate toolkit rainfall against ERA field records and explore yield vs climate, with plots.
Funded by the McKnight Foundation CRFS programme and supported by the CGIAR Climate Action Program through its Area of Work 1 (AoW1) — the Climate Data Hub — in partnership with AIMS RIC — see Funding & Acknowledgements.
The Climate Toolkit offers a unified, programmatic interface to:
- Retrieve climate data from CHIRPS, ERA5-Land, TerraClimate, IMERG, TAMSAT, CHIRTS-ERA5, ERA5, NEX-GDDP, NASA POWER, CMIP6 and SoilGrids
- Compute rainfall statistics, anomalies, and hazard indicators
- Compare climate trends over historical and seasonal periods
For user-facing historical daily climate work, the default module policy is
chirps_v3_daily_rnl + era5_land: CHIRPS v3 Daily RNL supplies precipitation.
The era5_land key reads ERA5-Land and supplies temperature plus companion variables such as humidity, wind,
and solar radiation. If a direct single-source historical fallback is needed,
prefer era5_land. Keep era_5 available for compatibility, diagnostics, and
comparison work, but do not treat it as the primary recommended source.
era5_land is the canonical key for ECMWF/ERA5_LAND/DAILY_AGGR.
The former agera_5 and agera5 spellings still select that same ERA5-Land
product and now emit a visible deprecation warning. They never selected the
separate Copernicus AgERA5 product. Compatibility aliases remain through 0.2.x;
new code, defaults and reports use era5_land. Existing agera_5 cache directories
are reused without changing their scientific content.
For no-GEE access, install the cloud extra on Python 3.12+ (pip install 'climate-toolkit[cloud]' or uv sync --extra cloud). CHIRPS v3 RNL can use
Dynamical and Hugging Face, with provider failover. Pair it with chirts_era5
for daily temperature through recent dates. Use --no-gee on the unified CLI
or with climate_toolkit.backend_policy(allow_gee=False): around Python
workflows; historical auto then uses this direct pair. Explicit providers,
cache provenance, QC and limits: direct cloud access.
If a Hugging Face chunk download fails, automatic CHIRPS requests can continue
to an eligible, configured Earth Engine backend. Explicit Hugging Face requests
report the transport failure directly.
Direct reads share source chunks across up to five missing years per batch and
save annual progress for retries. CHIRTS-ERA5's independent CHC backup remains
under validation.
ERA5-Land's official CDS cloud stores require a separate CDS key; that work is
shelved and they are not used by
the toolkit. The current no-GEE auto pair supplies rainfall and Tmax/Tmin.
For the complete fetch → climatology → statistics → hazards → comparison workflow,
run_pipeline accepts precip_source, temp_source and allow_gee=False, and
exports per-site reports with provenance. See the
full pipeline example.
chirts (1983–2016) is deprecated in favor of chirts_era5 for new work.
Legacy requests retain their original scientific meaning and caches; the old
product is no longer an automatic fallback. The direct pair supplies Tmax/Tmin
and rainfall, not humidity, wind or radiation.
TAMSAT remains available for completeness and Africa-focused precipitation
comparison work, but it is currently fragile and should not be treated as a
default or relied on for production workflows. It is precipitation-only, must
be paired with a temperature source for most analysis modules, and current
public access via JASMIN has shown slow performance and intermittent SSL /
download failures in live testing. Prefer chirps_v3_daily_rnl + era5_land for
normal user workflows.
Using it as a Python library? See the Use as a package guide for install, the seven public functions, sources, recipes, and troubleshooting.
Most historical gridded defaults and all current NEX-GDDP real-access paths use Earth Engine-backed retrieval. Do this first.
Important:
YOUR_PROJECT_IDbelow is placeholder text- replace it with your real Google Cloud Project ID
- do not paste literal string
YOUR_PROJECT_ID
python -c "import ee; ee.Authenticate()" export GCP_PROJECT_ID=YOUR_PROJECT_ID python -c "import ee; ee.Initialize(project='$GCP_PROJECT_ID'); print('EE init OK')"
Windows PowerShell:
python -c "import ee; ee.Authenticate()" $env:GCP_PROJECT_ID="YOUR_PROJECT_ID" python -c "import ee; ee.Initialize(project='$env:GCP_PROJECT_ID'); print('EE init OK')"
Required in .env.example:
GCP_PROJECT_ID- optional
EARTHDATA_USERNAME/EARTHDATA_PASSWORDfor sources that still use Earthdata-backed access
Verify your setup in one step (recommended before running any workflow):
climate-toolkit-gee-check # or: climate-toolkit gee-checkIt checks the project ID (flagging unedited placeholders), authentication, and
a live ee.Number(1).getInfo() round-trip, and prints a specific, copy-paste
fix — with both bash and PowerShell commands — for whichever step fails. Pass
--project <id> to test a specific project. Returns exit code 0 on success.
If you see:
Earth Engine project ID missing-> setGCP_PROJECT_IDProject 'projects/YOUR_PROJECT_ID' not found or deleted-> placeholder was not replaced with real project ID- auth refresh / DNS errors -> refresh Earth Engine auth and check internet/DNS
Just want to use the package? Install from PyPI:
pip install climate-toolkit
To develop the toolkit or run the examples/ scripts, set up from a clone instead:
-
Clone repository
git clone https://github.com/CGIAR-Climate-Data-Hub/climate-toolkit.git cd climate-toolkit -
Preferred setup with
uvmacOS / Linux:
uv venv source .venv/bin/activate uv sync --locked --group devWindows PowerShell:
uv venv .\.venv\Scripts\Activate.ps1 uv sync --locked --group dev
Repository commits
uv.lock, so normal setup should stay on locked sync. After dependency edits, refresh lockfile with:uv lock
Run commands through locked environment with:
uv run climate-toolkit-stats --help uv run python -c "import climate_toolkit; print('import ok')" uv run ruff check . uv run pytest -q
CI tests the base package on Python 3.10 and the
cloudandapiextras on Python 3.12. To run the cloud-provider and pipeline tests locally:uv sync --locked --group dev --extra cloud --extra api --python 3.12 uv run pytest -q
Distribution checks install the base wheel and source archive in fresh environments; Python 3.12+ also checks a fresh
cloudwheel installation. -
Fallback setup with
venv + pipmacOS / Linux:
python -m venv .venv source .venv/bin/activateWindows PowerShell:
python -m venv .venv .\.venv\Scripts\Activate.ps1If PowerShell blocks activation:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass .\.venv\Scripts\Activate.ps1
-
Install package with
pipfallbackStandard editable install:
python -m pip install --upgrade pip python -m pip install -e .Standard non-editable install:
python -m pip install .Fallback if you want raw dependency install only:
python -m pip install -r requirements.txt
Note —
climate-toolkit-*console scripts require the package to be installed. They are created only byuv syncorpip install -e .(orpip install .). A rawrequirements.txt-only install, or running from a fresh source checkout without installing, will not expose them, andclimate-toolkit-seasons(etc.) will report "command not recognized". In that case, run the equivalent module form instead, e.g.:python -m climate_toolkit.season_analysis.seasons --help
Every
climate-toolkit-<name>script maps to apython -m climate_toolkit.<module>entry point.Once installed, the tools are also available as subcommands of a single
climate-toolkitcommand, e.g.climate-toolkit fetch ...instead ofclimate-toolkit-fetch .... Runclimate-toolkit --helpto list all available commands. The standaloneclimate-toolkit-*scripts remain available as aliases. -
Copy environment template
cp .env.example .env
The toolkit reads configuration from the environment. It does not load
.env automatically — either export the variables in your shell, or run
commands through uv run --env-file .env ....
| Variable | Required for | Notes |
|---|---|---|
GCP_PROJECT_ID |
Earth Engine-backed routes (ERA5-Land via era5_land, ERA5, NEX-GDDP, GEE historical) |
Your real Google Cloud Project ID — see Earth Engine setup. GOOGLE_CLOUD_PROJECT / EE_PROJECT_ID are accepted as fallbacks. |
EARTHDATA_USERNAME / EARTHDATA_PASSWORD |
Sources still using Earthdata-backed access | Optional; only needed by those sources. |
Earth Engine authentication itself is stored separately (via
earthengine authenticate / ee.Authenticate()), not in these variables.
- Outputs default to
./outputs(created on demand and git-ignored). Most module CLIs also accept-o/--outputor--output-dirto write elsewhere. - Cache lives under
outputs/cache/<source>/...(e.g.outputs/cache/gee_xee_batch,outputs/cache/nex_gddp_batch). Fetches reuse cached frames for fast repeat runs.- Override the location with
--cache-dir <path>. - Force a fresh download with
--refresh-cache.
- Override the location with
- Both
outputs/and.tmp/are git-ignored, so nothing lands in version control by default.
After install, confirm the package and CLI surface are healthy (no network or Earth Engine required):
uv run python -c "import climate_toolkit; print(climate_toolkit.__version__)" uv run climate-toolkit --help # lists all subcommands uv run climate-toolkit fetch --help # per-command options uv run pytest -q # offline unit suite
Then verify Earth Engine connectivity before any real download (see the Earth Engine setup section for the preflight check).
Local build / install verification:
rm -rf .tmp/dist-release uv run python -m build --no-isolation --outdir .tmp/dist-release uv run twine check .tmp/dist-release/* python -m pip install .tmp/dist-release/climate_toolkit-*.whl
If you only want artifact verification without mutating current environment, rely on automated smoke tests and CI build checks.
For a reproducible runtime that does not depend on your local
Python version, use the provided Dockerfile. Reproducibility comes from three
pins: the base image (pinned by digest to CPython 3.10, matching CI), uv
(pinned to an exact release), and uv.lock (every dependency fixed to an exact
version + hash).
Build the image:
docker build -t climate-toolkit .Recommended: use the docker-run.sh wrapper. It deletes stale containers
from previous runs on every start, then launches a fresh one with --rm so it
also cleans up on exit — you never accumulate leftover containers. It builds the
image automatically on first use and forwards all arguments to the CLI:
./docker-run.sh --help GCP_PROJECT_ID=your-project ./docker-run.sh fetch --source nasa_power \ --lat -1.286 --lon 36.817 --from 2020-01-01 --to 2020-12-31
The wrapper mounts your Earth Engine credentials and outputs/ for you. Under
the hood it runs the plain commands below.
Offline smoke test — proves the environment reproduces, needs neither Earth Engine nor network:
docker run --rm climate-toolkit --help
docker run --rm --entrypoint python climate-toolkit \
-c "import climate_toolkit as ct; print(ct.__version__)"Earth Engine credentials are not baked into the image (they are per-user
OAuth). For Earth Engine-backed sources, mount your credentials read-only and
pass GCP_PROJECT_ID at runtime. Mount outputs/ so cached frames persist
across runs:
docker run --rm \ -e GCP_PROJECT_ID=your-project \ -v "$HOME/.config/earthengine:/home/app/.config/earthengine:ro" \ -v "$(pwd)/outputs:/app/outputs" \ climate-toolkit fetch --source nasa_power \ --lat -1.286 --lon 36.817 --from 2020-01-01 --to 2020-12-31
A docker-compose.yml wraps those mounts so you can run
docker compose run --rm toolkit <command> instead. NASA POWER needs no
credentials; the offline unit suite and CLI surface work without Earth Engine.
Container cleanup. Every documented command uses --rm, so a successful run
never leaves a container behind. Stale containers can only appear if a run
crashes or is started without --rm; the docker-run.sh wrapper sweeps those
before each start. To clean up manually at any time:
# Remove stopped containers built from the image docker ps -aq --filter ancestor=climate-toolkit --filter status=exited | xargs -r docker rm # Or, when using compose docker compose down --remove-orphans
- Published on PyPI as
climate-toolkit—pip install climate-toolkit. - Releases are automated via Trusted Publishing (OIDC, no stored tokens):
publishing a GitHub Release builds the package and uploads it to PyPI. Mark a
Release as a pre-release to route it to TestPyPI as a rehearsal instead. See
RELEASING.md. - Versions follow semantic versioning; PyPI versions are immutable, so each publish needs a new version number.
Reference note:
docs/distribution_workflow.md
For historical daily climate workflows, start with:
- precipitation:
chirps_v3_daily_rnl - temperature + companion variables:
era5_land
For most higher-level modules, --source auto or --source paired will route
to this historical default behavior.
Do not mix historical sources with nex_gddp in one run. NEX-GDDP future /
baseline workflows should be run separately from observed/reanalysis workflows.
climate-toolkit-fetch \ --source chirps_v3_daily_rnl \ --lat -1.286 \ --lon 36.817 \ --start 2020-01-01 \ --end 2020-01-10 \ --variables precipitation \ --stage preprocessed
Fallback module form:
python -m climate_toolkit.fetch_data.fetch_data \ --source chirps_v3_daily_rnl \ --lat -1.286 \ --lon 36.817 \ --start 2020-01-01 \ --end 2020-01-10 \ --variables precipitation \ --stage preprocessed
New here? See docs/example_workflow.md for a full end-to-end story (fetch → validate → climatology → seasons → stats → periods → hazards → projections) with runnable commands.
Main entry point:
climate-toolkit fetch(or the aliasclimate-toolkit-fetch)
Key options:
--source: exact source key such aschirps_v3_daily_rnl,chirps_v2,era5_land,era_5,nex_gddp,nasa_power--stage:raw,transformed,preprocessed--variables: comma-separated toolkit variable names--output: optional output file--format:print,csv,json--site/--sites-csv: many-site fetch path for GEE/Xee-backed sources--cache-dir: stable local cache root for repeat reuse
NEX-GDDP requires:
--model--scenario- prior Earth Engine authentication
GCP_PROJECT_ID
Current package runtime uses Earth Engine NEX-GDDP version 1.1, not 1.2.
NEX-GDDP humidity note:
- toolkit now supports relative humidity from Earth Engine band
hurs - this enables future-path livestock THI where
hursis available hursis not universal across full Earth Engine NEX-GDDP catalog, so some model / scenario / year combinations still fail by design with clear error- toolkit default 18-model curated pool avoids several catalog-documented humidity-gap models, so standard toolkit runs are safer than unrestricted full-catalog model selection
Livestock THI source support:
| Source | Status | Notes |
|---|---|---|
era5_land |
supported | humidity derived from dewpoint + air temperature in current fetch pipeline |
nasa_power |
supported | humidity available from current NASA POWER fetch path |
ghcn_daily |
supported when available | uses station humidity when RHAV exists for chosen station and window |
gsod |
supported when available | uses station humidity when humidity field exists for chosen station and window |
custom_station |
supported when available | uploaded file must include humidity / RH column |
nex_gddp |
conditionally supported | uses Earth Engine hurs; some model / scenario / year combinations lack that band |
era_5 |
uncertain | current toolkit ERA5 fetch configuration does not define a humidity band for operational THI use |
chirps_v2 |
not supported | precipitation-only source |
chirps_v3_daily_rnl |
not supported | precipitation-only source |
imerg |
not supported | precipitation-only source |
tamsat |
not supported | no humidity data |
chirts_era5, deprecated chirts |
not supported | temperature-only sources; humidity must come from a companion product |
Python users can inspect same support map directly:
from climate_toolkit.climatology import describe_thi_method, describe_thi_source_support print(describe_thi_source_support()) print(describe_thi_method()["profiles"]["cattle_dairy"])
Dedicated method guide:
Human heat first-pass note:
- toolkit now also exposes xclim-backed
humidexhelper functions for people - this is still phase-1 support, but
calculate_hazardsnow includes generic humidex screening classes and humidex day-count summaries when humidity-backed inputs exist climate_statisticsandcompare_periodsnow surfacehumidexwhen humidity or dewpoint-backed inputs exist- in
paired/ composite historical workflows, human-heat provenance comes from temperature-side companion variables, not precipitation-side source WBGTandUTCIare intentionally deferred until wind/radiation support is more coherent across intended workflows
Python users can inspect current human-heat choice directly:
from climate_toolkit.climatology import ( build_human_heat_source_bundle, compute_daily_humidex, describe_human_heat_method, describe_human_heat_source_support, ) print(describe_human_heat_method()["metric"]) print(describe_human_heat_source_support()) print(build_human_heat_source_bundle(source="paired", precip_source="chirps_v3_daily_rnl", temp_source="era5_land"))
Dedicated method guide:
Example:
env GCP_PROJECT_ID=YOUR_PROJECT_ID climate-toolkit-fetch \ --source nex_gddp \ --lat -1.286 \ --lon 36.817 \ --start 2050-01-01 \ --end 2050-01-05 \ --model MRI-ESM2-0 \ --scenario ssp245 \ --variables precipitation,max_temperature,min_temperature,humidity \ --stage raw
climate-toolkit-seasonsclimate-toolkit-seasons-ensemble
Fixed-season example:
climate-toolkit-seasons \ --location="-1.286,36.817" \ --start-year=2020 \ --end-year=2020 \ --source=paired \ --precip-source=chirps_v3_daily_rnl \ --temp-source=era5_land \ --fixed-season="03-01:05-31"
climate-toolkit-statsclimate-toolkit-stats-ensemble
climate-toolkit-stats \ --location="-1.286,36.817" \ --start-year=2020 \ --end-year=2020 \ --source=paired \ --precip-source=chirps_v3_daily_rnl \ --temp-source=era5_land \ --fixed-season="03-01:05-31"
climate-toolkit-periodsclimate-toolkit-periods-ensemble
NEX-GDDP baseline-vs-future example:
climate-toolkit-periods-ensemble \ --location="-1.286,36.817" \ --baseline-start=1995 \ --baseline-end=2013 \ --future-start=2041 \ --future-end=2060 \ --scenarios=ssp245 \ --fixed-season="03-01:05-31" \ --livestock-type cattle_dairy
Add --uncertainty-html ensemble.html for annual and seasonal model spread, paired changes, and model contribution counts.
All NEX-GDDP ensemble CLIs now accept:
--model-workers: bounded model-level parallelism for ensemble jobs
This currently applies to:
climate-toolkit-periods-ensembleclimate-toolkit-stats-ensembleclimate-toolkit-seasons-ensembleclimate-toolkit-hazards-ensembleclimate-toolkit-climatologywhen--source nex_gddp
Practical guidance:
--model-workers 1: serial debugging or very constrained environments--model-workers 8: default balanced setting--model-workers 12: heavier workstation run--model-workers 16: aggressive upper-end setting to test carefully
In restricted environments, the toolkit may fall back to serial execution if process workers are blocked. When that happens, the CLI prints a warning and continues rather than failing the entire run.
JSON outputs from ensemble workflows now include timing metadata under
metadata.timing, including worker request/usage fields and aggregate timing
such as total_seconds and mean_model_seconds.
climate-toolkit-hazardsclimate-toolkit-hazards-ensemble
For evaluate_hazards and climate-toolkit-hazards, fixed seasons are selected
by their start date, including both request bounds. For example, asking for
10-01:01-31 with dates in calendar year 2010 returns 1 October 2010 through
31 January 2011. The fetch includes spin-up before onset and all days through
cessation. For one season, read result["season_info"] and
result["season_statistics"]. For multiple seasons, read result["assessments"].
NEX-GDDP hazards (--source nex_gddp, also evaluate_hazards(..., source="nex_gddp"))
accept --model / --scenario. --scenario defaults to historical when the
requested window ends before 2015, so pre-2015 windows work without extra flags
(a window that crosses 2015 needs an explicit scenario — no single NEX-GDDP
scenario spans the historical/SSP boundary):
env GCP_PROJECT_ID=YOUR_PROJECT_ID climate-toolkit-hazards \
maize \
--location=-0.776,37.66 \
--date-from 1995-01-01 \
--date-to 2013-12-31 \
--source nex_gddp \
--model GFDL-ESM4 \
--fixed-season '10-17:01-09'climate-toolkit-weather-station-downloadclimate-toolkit-weather-station-compare
Candidate station review:
climate-toolkit-weather-station-download \ --station-source auto \ --selection-mode list \ --station-lat -1.286 \ --station-lon 36.817 \ --start 2011-01-01 \ --end 2020-12-31 \ --variables precipitation,max_temperature,min_temperature \ --max-distance-km 100 \ --report-prefix outputs/weather_station/nairobi_auto_candidates
Station-vs-grid comparison:
climate-toolkit-weather-station-compare \ --station-source auto \ --station-lat -1.286 \ --station-lon 36.817 \ --target-elevation-m 1667 \ --start 2011-01-01 \ --end 2020-12-31 \ --selection-mode auto \ --auto-select auto-1 \ --grid-source paired \ --grid-source nasa_power \ --precip-source chirps_v3_daily_rnl \ --temp-source era5_land \ --variables precipitation,max_temperature,min_temperature \ --output outputs/weather_station/nairobi_station_vs_grid.json
Custom station files are also supported in weather-station and selected historical-analysis workflows. Current custom station flags include:
--custom-station-file--custom-station-vars--custom-temp-unit--custom-precip-unit
Top-level stable Python API names:
from climate_toolkit import fetch_climate_datafrom climate_toolkit import analyze_climate_statisticsfrom climate_toolkit import compare_climate_periodsfrom climate_toolkit import compare_climate_sourcesfrom climate_toolkit import evaluate_hazardsfrom climate_toolkit import download_station_datafrom climate_toolkit import compare_station_to_grids
Notebook-safe example:
from datetime import date from climate_toolkit import fetch_climate_data from climate_toolkit.fetch_data.source_data.sources.utils.models import ClimateVariable df = fetch_climate_data( source="chirps_v3_daily_rnl", location_coord=(-1.286, 36.817), variables=[ClimateVariable.precipitation], date_from=date(2020, 1, 1), date_to=date(2020, 1, 10), stage="preprocessed", )
In Jupyter, prefix shell commands with !:
!python -m climate_toolkit.fetch_data.fetch_data --helpclimate-toolkit-climatology writes annual and monthly climatology PNGs by
default under ./outputs. Those plots now rely on the standard package
dependency set, including matplotlib.
NASA POWER example:
climate-toolkit-climatology \
--location="-1.286,36.817" \
--start-year=1991 \
--end-year=2020 \
--source=nasa_powerEarth Engine-backed historical example:
export GCP_PROJECT_ID=YOUR_PROJECT_ID climate-toolkit-climatology \ --location="-1.286,36.817" \ --start-year=1991 \ --end-year=2020 \ --source=era5_land
Important source notes:
chirps_v3_daily_rnlandchirts_era5prefer direct public cloud access with Python 3.12+ and thecloudextra. Use--no-geeto prohibit GEE fallback.era5_land,era_5,chirps_v2, deprecatedchirts,imergand other GEE-only routes need Earth Engine auth plusGCP_PROJECT_ID.era_5daily coverage currently ends on2020-07-09in this package. Useera5_landfor a full1991-2020climatology window, or stop ERA5 at2019.chirps_v2/chirps_v3_daily_rnlare precipitation-only, so climatology will omit temperature outputs.chirts_era5and deprecatedchirtsare temperature-only, so climatology omits precipitation outputs.
SPEI and xclim helpers are library functions, not standalone console scripts.
Use them from Python after fetching/preprocessing climate data. VPD helpers use
xclim for thermodynamic calculation and prefer CHC-consistent
moisture-informed inputs (relative_humidity or dewpoint) when available:
from climate_toolkit.climatology.spei import ( compute_monthly_spei, prepare_monthly_climatic_water_balance, ) from climate_toolkit.climatology import summarize_vpd_period from climate_toolkit.climatology.xclim_reference import ( compute_xclim_precip_indices, ) monthly_balance = prepare_monthly_climatic_water_balance(df, lat=-1.286) spei_12 = compute_monthly_spei(monthly_balance, scale=12) xclim_precip = compute_xclim_precip_indices(df) vpd = summarize_vpd_period(df)
An optional FastAPI service in apis/ exposes the toolkit over HTTP — a JSON
API under /api/v1/* plus simple HTML pages for interactive use. It is not
required for CLI/library use, so its dependencies are an optional extra.
Install and run:
# install the API extra (fastapi/uvicorn/jinja2/python-multipart) uv sync --extra api # or: pip install -e ".[api]" # run the dev server from the repo root uv run uvicorn apis.main:app --reload
Then open:
http://127.0.0.1:8000/— HTML landing page / formshttp://127.0.0.1:8000/docs— interactive OpenAPI (Swagger) docshttp://127.0.0.1:8000/api/v1/data/sources— example JSON endpoint
Dockerfile.api builds a reproducible image (base pinned by digest, uv and
uv.lock pinned) that installs the api extra and serves the app with uvicorn
in production mode — no --reload. Build and run:
docker build -f Dockerfile.api -t climate-toolkit-api . # Offline check — the app boots without Earth Engine: docker run --rm -p 8000:8000 climate-toolkit-api # then browse http://127.0.0.1:8000/ (and /health for the readiness probe)
Earth Engine credentials are not baked into the image (they are per-user
OAuth). For GEE-backed requests, mount your credentials read-only and pass
GCP_PROJECT_ID; mount outputs/ so generated plots persist:
docker run --rm -p 8000:8000 \ -e GCP_PROJECT_ID=your-project \ -v "$HOME/.config/earthengine:/home/app/.config/earthengine:ro" \ -v "$(pwd)/outputs:/app/outputs" \ climate-toolkit-api
The image runs as a non-root user, exposes port 8000, and defines a
HEALTHCHECK against /health. For a public deployment, put it behind a
reverse proxy (TLS termination), restrict the wildcard CORS origins in
apis/main.py to your front-end origin, and run multiple workers
(--workers N) as needed.
Endpoints wrap the same functions as the CLI (data, statistics, hazards,
compare, seasons, climatology, compare-datasets), so the Earth Engine
auth and GCP_PROJECT_ID expectations from
Environment variables apply to any GEE-backed request.
Supported end-user CLI contracts:
climate-toolkit-fetchclimate-toolkit-seasonsclimate-toolkit-seasons-ensembleclimate-toolkit-statsclimate-toolkit-stats-ensembleclimate-toolkit-periodsclimate-toolkit-periods-ensembleclimate-toolkit-hazardsclimate-toolkit-hazards-ensembleclimate-toolkit-weather-station-downloadclimate-toolkit-weather-station-compareclimate-toolkit-compare-datasetsclimate-toolkit-climatology
CLI implementation note:
climate-toolkit-climatologyis the current Typer prototype from issue#34- the remaining public CLI entry points still use their existing
argparsewrappers while compatibility and migration cost are evaluated - current decision from issue
#34: no broad CLI rewrite yet; any future Typer migration should be command-by-command, keep existing console-script names, and preservemain()entry points
Preferred stable import paths:
- top-level package for end-user workflows:
climate_toolkit.fetch_climate_dataclimate_toolkit.analyze_climate_statisticsclimate_toolkit.compare_climate_periodsclimate_toolkit.compare_climate_sourcesclimate_toolkit.evaluate_hazardsclimate_toolkit.download_station_dataclimate_toolkit.compare_station_to_grids
- explicit subpackage roots for supported advanced use:
climate_toolkit.fetch_dataclimate_toolkit.weather_stationclimate_toolkit.crop_calendarclimate_toolkit.climatology
Avoid depending on deep internal modules unless you are doing package development. Examples of internal paths that are importable but not stable contracts:
climate_toolkit.fetch_data.source_data.source_dataclimate_toolkit.fetch_data.preprocess_data.preprocess_dataclimate_toolkit.fetch_data.transform_data.transform_dataclimate_toolkit.fetch_data.gee_xee_batchclimate_toolkit.fetch_data.nex_gddp_batchclimate_toolkit.fetch_data.cache_inventoryclimate_toolkit.fetch_data.source_data.sources.utils
GEE/Xee-backed fetches can be slow on a cold run because the toolkit has to retrieve and standardize the source data before writing cache files. Once the cache exists, repeat runs can be near-instant for the same source, site, date window, and variable set.
For example, a live three-site, one-year benchmark on June 13, 2026 using:
chirps_v3_daily_rnlcold cache: about 22 secondsera5_landwith precipitation, temperature, humidity, wind, and solar cold cache: about 78 seconds- either source from warm cache: about 0.75 seconds
If you want cache reuse across sessions, pass a stable project-local
--cache-dir such as outputs/cache/....
First run may take tens of seconds to minutes for GEE/Xee-backed workflows. Repeat runs using same cache can be near-instant.
Observed live examples:
chirps_v3_daily_rnl, 3 sites, 1 year, cold cache: about22sera5_land, 3 sites, 1 year, cold cache with companion variables: about78s- warm-cache rerun for same requests: about
0.75s
For project work, prefer stable cache roots under outputs/cache/....
CLI/API name remains regional_fast, but this means regional screening subset,
not guaranteed fast runtime.
Decision memos:
NEX-GDDP ensemble runs are still expensive even after model-worker parallelism. The practical speedup is bounded by:
- Earth Engine / Xee request latency
- download chunk size
- number of models and scenarios
- per-model daily time-window length
- local process and memory limits
Use regional screening pools when you want a smaller candidate set for first pass analysis, and expand to larger model pools only when the question requires it.
Use tamsat only as optional precipitation partner, not primary recommended
historical source.
- pair it with temperature source such as
era5_land - expect slower runs and possible download instability
- use as comparison / sensitivity source, not dependable default
climate_toolkit/
├── calculate_hazards/ # Hazard and risk workflows
├── climate_statistics/ # Seasonal / climatological stats
├── compare_periods/ # Baseline vs focal/future comparisons
├── fetch_data/ # Climate data retrieval and harmonization
├── season_analysis/ # Onset / cessation and season summaries
└── weather_station/ # Station download, selection, comparison
- All configuration values (e.g., API keys) are managed via
.envusingpython-dotenv. - Modular dataset handlers are found in
climate_toolkit/fetch_data/source_data/sources/, each withDownloadDataclasses. - Common utilities like enums and settings are stored in
climate_toolkit/fetch_data/source_data/sources/utils/. - Current package architecture summary:
analysis/package_architecture_summary.md - NEX-GDDP real-access R&D note:
analysis/nex_gddp_access_rnd.md nex_gddpnow uses real Earth Engine/Xee retrieval. It requires Earth Engine auth plusGCP_PROJECT_ID.- Current
nex_gddpEarth Engine backend uses dataset version1.1. Future1.2sourcing is tracked as follow-up work, not current runtime behavior. nex_gddphumidity now uses Earth Enginehurswhen available; toolkit raises explicit errors for documented missing-band cases instead of opaque fetch failures.- Arid-region NEX rainfall-spike warning rationale and literature links are documented in
analysis/nex_gddp_access_rnd.md. - package install shape is tested through
pyproject.toml,uv.lock, and console-script entrypoints - preferred development install is
uv sync --locked --group dev - fallback editable install remains
python -m pip install -e . - non-editable smoke install path is
python -m pip install .
Current source-of-truth:
analysis/package_architecture_summary.md
This README section is short operational summary. Detailed architecture, boundary, and maintenance rules live in file above.
Current architectural principles:
fetch_datais central ingest and harmonization layer- historical and future-projection workflows share as much interface as possible, but do not require identical backends
- cache reuse under
outputs/cache/...is part of runtime design, not incidental implementation detail - stable user contracts are top-level Python API names plus CLI entry points from
pyproject.toml - deep internal modules remain non-stable development surface
Architecture flow diagram source:
assets/package_architecture_overview.mmd
flowchart TD
A["User CLI / Python API"] --> B["fetch_data"]
B --> B1["source_data"]
B1 --> B2["transform_data"]
B2 --> B3["preprocess_data"]
B3 --> C["season_analysis"]
B3 --> D["climate_statistics"]
B3 --> E["calculate_hazards"]
B3 --> F["compare_datasets"]
C --> D
D --> G["compare_periods"]
D --> H["ensemble_periods"]
I["weather_station.download"] --> J["station_selector / NOAA / custom station"]
J --> K["weather_station.compare"]
K --> B3
L["crop_calendar"] --> C
L --> D
L --> G
L --> H
M["climatology / xclim"] --> D
M --> G
M --> K
Core current-state modules:
| Module | Role | Key dependencies |
|---|---|---|
fetch_data |
source dispatch, harmonization, stage handling, cache routing | source_data, transform_data, preprocess_data, GEE/Xee helpers |
season_analysis |
ET0, water balance prep, auto/fixed season detection | fetched daily climate series |
climate_statistics |
raw/overall/season/LTM/SPEI reductions | fetch_data, season_analysis, climatology, crop_calendar |
compare_periods |
baseline vs focal/future comparisons | climate_statistics payload contracts |
calculate_hazards |
hazard indicators and crop/soil-water metrics | fetched/preprocessed climate series, hazard params |
compare_datasets |
source-vs-source comparison workflow | shared fetch pipeline |
weather_station |
station discovery, ingestion, selection, station-vs-grid validation | NOAA/custom station inputs, gridded fetch layer |
crop_calendar |
GGCMI crop calendar lookups and presets | season_analysis, climate_statistics, compare_periods |
climatology |
SPEI and xclim-backed climatology helpers, including CHC-aligned moisture-informed VPD support | climate_statistics, compare_periods, weather_station |
Notes:
fetch_datais central shared ingest layer for most packageseason_analysisfeedsclimate_statisticsclimate_statisticsdefines payload shape consumed bycompare_periods- weather-station workflows run parallel to gridded path, but compare against same gridded sources and can override some historical variables
- source/backend reality still differs by dataset; see
analysis/source_access_matrix.md
These are the API statuses that will be applicable to this application.
| Status Code | Status | Message |
|---|---|---|
| 20X | REQUEST_SUCCESSFUL | "Your request was received and data processed successfully" |
| 40X | REQUEST_UNSUCCESSFUL | "Your request was received but there was an issue with processing the data" |
| 50X | SERVICE_UNREACHABLE | "Your request was not received by the server" |
This is a basic structure of the API response format containing the mandatory fields. This enables the responses for various services consumed in this toolkit to have a standardised response format. It should be noted that the payload key-value pairs will depend on the return values of the application logic:
status_code: integerstatus: stringmessage: stringdata: json
{
"status_code": 200,
"status": "REQUEST_SUCCESSFUL",
"message": "Your request was received and data processed successfully",
"data": {
# Payload depends on the app logic's return values
"key1": "value1",
"key2": "value2"
}
}
| # | Practice | Description |
|---|---|---|
| 1 | Commit Early and Often | Don't wait until a large feature is complete. Commit small, logical, and self-contained changes. |
| 2 | Atomic Commits | Each commit should represent a single, coherent change or a small set of related changes. If you're fixing two different bugs, create two separate commits. |
| 3 | Don't Commit Half-Done Work (to shared branches) | While local commits can be frequent, avoid pushing incomplete or broken code to shared development branches. Use "git stash" if you need a clean working directory temporarily. |
| 4 | Test Before Committing | Ensure your code works as expected and passes tests before committing. |
| 5 | Review Before Committing | Use "git diff" to review your own changes before committing to catch unintended modifications. |
| 6 | Conventional Commits | Consider adopting a convention like Conventional Commits (feat:, fix:, chore:, docs:, ci:, refactor:, test:) to categorize changes and enable automated changelog generation. For example, "feat: Add CHIRPS as a climate data source". Ref: https://www.conventionalcommits.org |
| 7 | Consistent Naming Conventions | Establish clear and consistent naming conventions for branches (e.g., feat/feature-name, fix/issue-description, refactor/performance-improvement, etc). |
| 8 | Pull Regularly | Each feature or fix should be developed on a dedicated branch. These branches should be short-lived and merged back into a main development branch (e.g., develop or main) as soon as the work is complete and reviewed. Pull frequently to avoid merge conflicts. |
| 9 | Branching Strategies | GitLab Flow will be used. It will have the following branches: a. main: This branch should always be stable and deployable. Direct commits to this branch should be prohibited; all changes must come through pull requests. b. staging: This branch is for the UAT/QA environment. Direct commits to this branch should be prohibited; all changes must come through pull requests. Maintainers can have "force push" access. |
| 10 | Well-Documented Pull Requests (PRs) | Summarize the PR's purpose effectively in the subject. The PR should also have a detailed description that covers: a. Problem Statement: Clearly describe the problem or feature addressed by the PR. b. Solution Overview: Explain how the PR solves the problem or implements the feature. c. Technical Details (if necessary): Provide any necessary technical context, architectural decisions, or trade-offs. d. Screenshots/Videos: For UI changes, include screenshots or short videos to demonstrate the changes. e. Testing Instructions: Provide clear steps for reviewers to test the changes, including any specific configurations or data needed. f. Related Issues/Tickets: Link to relevant issues in your issue tracker. |
| 11 | DevOps | Automating the build, test, and deployment process ensures that code changes are integrated frequently and validated quickly. This catches issues early and provides rapid feedback. This will be implemented using GitHub Actions since it is native to GitHub. |
| 12 | Conversation Trails | Keep implementation discussions on the ticket in the Kanban system. This makes it easier to maintain a trail of the conversations and decisions regarding a proposed feature or fix. If discussions are held outside of the ticket (e.g., on Teams due to confidentiality), the conclusions from those discussions should be transferred to the ticket itself. This will still allow the project to maintain an trail of the conversation and decisions affecting the implementation of the feature. |
We welcome PRs and suggestions!
- Fork the repo
- Work in a feature branch
- Follow module layout and Ruff checks
- Submit a pull request with a clear description using the repository PR template
- Complete every applicable PR template section, especially problem statement, implementation notes, data/auth/runtime notes, testing, and related issues
Local quality commands:
uv sync --locked --group dev rm -rf .tmp/dist-release uv run python -m build --no-isolation --outdir .tmp/dist-release uv run twine check .tmp/dist-release/* uv run ruff check . uv run ruff format . uv run pytest -q
CI currently enforces the low-noise Ruff lint baseline with ruff check ..
ruff format is available for local cleanup, but repository-wide formatter
enforcement should come in a later cleanup slice rather than the initial Ruff
adoption PR.
Toolkit supports:
- NOAA station discovery and download with
ghcn_daily,gsod, orauto - station-vs-grid comparison against historical gridded products, with optional monthly and seasonal diagnostics via
--diagnostics-html FILE - custom station CSV/JSON ingestion
- custom station override into historical climate analysis
Detailed guide:
Before first run:
--station-lat/--station-lonare focal site coordinates, not necessarily final chosen station coordinates- start with
--selection-mode listif you do not already know station quality nearby - evaluate completeness by variable before asking for full precip + Tmax + Tmin bundle
- if DEM-based elevation guard matters, either provide
--target-elevation-mor make sure Earth Engine auth andGCP_PROJECT_IDare valid
--station-sourceghcn_daily: NOAA GHCN-Daily onlygsod: NOAA GSOD onlyauto: rank candidates across both NOAA backendscustom_csv: user-supplied CSV/JSON
--selection-modelist: inspect candidates only; no station data downloadspecified: use--station-idauto: toolkit chooses station(s) inside current guardrails
--auto-selectauto-1,auto-2,auto-3, ...auto-all: use as many eligible stations as current--max-auto-stationscap allows
- compare workflow also has
--selection-strategyall_vars_single_station: one station must carry all requested variablesbest_per_variable: toolkit may use different nearby stations for precipitation vs temperature
Default guardrails:
- search radius:
50 km - maximum elevation difference:
500 m - minimum per-variable completeness:
0.70 - maximum auto-selected stations:
10
Completeness relaxation:
- strict threshold first: requested
--min-completeness-ratio - relaxed sequence after that:
0.50 -> 0.30 -> 0.10 - if still no station passes and fallback allowed, toolkit may keep stations that satisfy only some requested variables
This means station selection is variable-by-variable, not only one overall coverage score.
Find nearby observed stations and create review artifacts:
climate-toolkit-weather-station-download \ --station-source auto \ --selection-mode list \ --station-lat -1.286 \ --station-lon 36.817 \ --start 2011-01-01 \ --end 2020-12-31 \ --variables precipitation,max_temperature,min_temperature \ --max-distance-km 100 \ --report-prefix outputs/weather_station/nairobi_auto_candidates \ --open-report
Outputs:
- candidate CSV
- candidate JSON
- candidate HTML map
Candidate review is best first step when:
- you do not know which stations exist nearby
- you want to inspect completeness by variable before download
- you want map showing focal coordinates vs candidate station positions
Map notes:
--open-reporttries to open HTML map automatically- map uses live web tiles, so background basemap needs internet
- report shows only stations discoverable through current toolkit NOAA backends
climate-toolkit-weather-station-download \ --station-source auto \ --selection-mode auto \ --auto-select auto-1 \ --station-lat -1.286 \ --station-lon 36.817 \ --start 2011-01-01 \ --end 2020-12-31 \ --variables precipitation,max_temperature,min_temperature \ --stage preprocessed
Useful variants:
- pin one station with
--selection-mode specified --station-id <ID> - widen search with
--max-distance-km - supply known elevation with
--target-elevation-m - disable completeness guard for exploratory work with
--disable-completeness-guard - keep raw values with
--stage raw
Replace <REPLACE_WITH_YOUR_STATION.csv> below with a real CSV path (the
required columns are documented under "Expected custom file shape" just below):
climate-toolkit-weather-station-download \ --station-source custom_csv \ --custom-station-file <REPLACE_WITH_YOUR_STATION.csv> \ --custom-station-name "My station" \ --station-lat -1.286 \ --station-lon 36.817 \ --start 2020-01-01 \ --end 2020-12-31 \ --variables precipitation,max_temperature,min_temperature \ --custom-temp-unit c \ --custom-precip-unit mm
Expected custom file shape:
- required:
date- at least one requested climate variable
- accepted precipitation aliases:
precipitation,precip,rain,rainfall,prcp
- accepted temperature aliases:
tmax/max_temperaturetmin/min_temperaturetmean/mean_temperature
- optional metadata:
station_id,station_name,lat,lon,elevation
Declare units explicitly:
--custom-temp-unit c|f|k--custom-precip-unit mm|inch|tenth_mm
Custom file notes:
- toolkit normalizes aliases, subsets requested period, converts units, then caches normalized outputs
- if
mean_temperaturemissing butmax_temperatureandmin_temperatureexist, toolkit derives mean temperature - if
station_id,station_name,lat,lon, orelevationmissing, toolkit fills best-effort metadata from CLI inputs and file name - if uploaded file has no rows in requested window, historical override workflows fall back to gridded values with warning
climate-toolkit-weather-station-compare \ --station-source auto \ --station-lat -1.286 \ --station-lon 36.817 \ --start 2011-01-01 \ --end 2020-12-31 \ --selection-mode auto \ --auto-select auto-1 \ --grid-source paired \ --grid-source nasa_power \ --precip-source chirps_v3_daily_rnl \ --temp-source era5_land \ --variables precipitation,max_temperature,min_temperature \ --output outputs/weather_station/nairobi_station_vs_grid_2011_2020.json
Comparison intent:
- compare observed station data against historical gridded products near same location
- assess which historical grid source best represents local observed conditions
- not direct future
nex_gddpvalidation workflow
Current grid-source notes:
- better independence:
era5_land,era_5,nasa_power,imerg - partly station-informed:
chirps_v2,chirps_v3_daily_rnl,chirts_era5,chirts,paired,terraclimate,auto - comparison output warns when selected grid source is not fully independent from station-based validation
Output layers include:
- daily metrics
- monthly aggregated metrics
- seasonal aggregated metrics
- annual overlap summary
- xclim-derived annual precipitation reference indices when overlap is dense enough
- pooled multi-station summaries when more than one station contributes
Interpretation caution:
- daily precipitation correlation often looks weak even when monthly or seasonal agreement is useful
- annual and xclim summaries should only be trusted when overlap coverage is dense enough
pairedis mixed-source workflow, so interpret independence using underlying precip and temperature products
The --custom-station-* flags are optional — use them only if you have a
real station CSV. Run the base command without them first:
climate-toolkit-stats \
--location="-1.286,36.817" \
--start-year=2020 \
--end-year=2020 \
--source=paired \
--precip-source=chirps_v3_daily_rnl \
--temp-source=era5_landTo overlay your own station observations, add the override flags and replace
<REPLACE_WITH_YOUR_STATION.csv> with the path to an actual CSV (see
Custom Station File for the required columns):
climate-toolkit-stats \ --location="-1.286,36.817" \ --start-year=2020 \ --end-year=2020 \ --source=paired \ --precip-source=chirps_v3_daily_rnl \ --temp-source=era5_land \ --custom-station-file <REPLACE_WITH_YOUR_STATION.csv> \ --custom-station-vars precipitation,max_temperature,min_temperature \ --custom-station-name "My station"
Copying the second command unchanged will fail with
FileNotFoundError: Custom station file not found: ...\<REPLACE_WITH_YOUR_STATION.csv>— that means the placeholder still needs to be replaced with a real path.
Override workflow purpose:
- substitute observed station variables into historical season/statistics workflows
- keep gridded variables for anything not supplied by station file
Current override entry points:
climate-toolkit-statsclimate-toolkit-seasons
Weather-station cache uses:
outputs/cache/weather_stations/ghcn_dailyoutputs/cache/weather_stations/gsodoutputs/cache/weather_stations/customoutputs/cache/weather_stations/dem_anchor
Typical contents:
- NOAA station metadata / inventories
- downloaded station files
- custom-station normalized CSV plus manifest JSON
- DEM-derived focal elevation lookups
- candidate review artifacts under chosen
--report-prefix
Keep cache under project-local outputs/cache/... so repeat runs can reuse saved files.
If station selection fails:
- widen
--max-distance-km - request fewer variables
- lower
--min-completeness-ratio - inspect
--selection-mode listoutput before disabling guards - use
best_per_variableonly if mixed-station interpretation is acceptable
- some locations have very sparse observed coverage, especially for full precip + tmax + tmin overlap
autoonly sees current NOAA backends plus user-supplied custom files; not all global station archives- compare workflow is historical-grid only; future NEX-GDDP station evaluation remains separate methodological work
- candidate review map is HTML, not full GIS export
- mixed-station compare strategies can improve variable coverage, but reduce simplicity of interpretation
- Earth Engine-backed helper pieces such as anchor elevation need valid project/auth if DEM lookup is used automatically
Not all toolkit metrics belong to same methodological family.
Standard / xclim-audited examples:
- precipitation total
- rainy days
- dry days
NDDdry-day count semantics (< 1 mm/day)NTx35/NTx40hot-day count semantics- daily precipitation intensity style metrics
- max 1-day precipitation
- max 5-day precipitation in weather-station reference comparisons
- core Tmax / Tmin / Tavg period summaries
- nearest-reference SPI / SPEI comparisons
Custom, non-xclim metrics:
NDWSNDWL0WRSI- crop-calendar-aware season windows
- crop-threshold hazard interpretation
Important distinction:
- some hazard counts are xclim-audited (
NDD,NTx35,NTx40) - hazard bands / stress labels built on those counts are still Atlas-inspired provisional interpretation, not xclim outputs
Reference note:
This project is licensed under the MIT License.
This toolkit was developed as part of the project Advancing Climate Data Integration in Agroecological Research, funded by the McKnight Foundation through its Global Collaboration for Resilient Food Systems (CRFS) programme. The work was led by the Alliance of Bioversity International and CIAT, in partnership with AIMS RIC.
This work was supported by the CGIAR Climate Action Program through its Area of Work 1 (AoW1) — the Climate Data Hub (CDH), which funds and coordinates the climate-data infrastructure this toolkit is part of. We acknowledge the CGIAR Trust Fund and its contributors.

