Using climate-toolkit as a Python package¶
A practical, end-to-end guide to installing and using climate_toolkit as a
library from your own Python code. Every credential-free example here was run
against the real package and API.
Status note. The package is
climate_toolkit(import name), distributed asclimate-toolkiton PyPI. Direct CHIRPS v3 and CHIRTS-ERA5 access requires version 0.2.0 or later.
Prefer to try it live? The companion notebook
examples/climate_toolkit_colab.ipynb
runs this guide's credential-free examples end-to-end in Google Colab — no
install or setup on your machine.
Table of contents¶
- What you get
- Requirements
- Installation
- Verify the install
- Credentials by data source
- Quick start (no credentials)
- Earth Engine setup
- Seven analysis functions
- Data sources reference
- Variables reference
- Caching and outputs
- Recipes
- Using it in Jupyter / your own project
- Troubleshooting
- Getting more help
1. What you get¶
New here?
For a 5-minute install and first run, start with Getting started. This page is the fuller reference — every public function, the sources and variables, caching, recipes, and troubleshooting.
climate_toolkit is a location-based climate analysis library. From a single
import climate_toolkit as ct you can call these seven analysis functions. The API overview also lists run_pipeline and backend_policy.
| Function | What it does |
|---|---|
fetch_climate_data |
Download daily climate data for a point as a pandas DataFrame |
analyze_climate_statistics |
Seasonal climatology, water balance, SPI/SPEI over a multi-year window |
evaluate_hazards |
Crop/livestock hazard assessment for a growing season |
compare_climate_periods |
Diff a focal year against a baseline climatology |
compare_climate_sources |
Side-by-side comparison of gridded datasets for one site |
download_station_data |
Fetch daily observations from nearby weather stations |
compare_station_to_grids |
Validate gridded datasets against station observations |
Data comes from CHIRPS, ERA5-Land, TerraClimate, IMERG, TAMSAT, CHIRTS-ERA5, ERA5, NEX-GDDP, NASA POWER, CMIP6, SoilGrids, plus GHCN-Daily / GSOD stations.
2. Requirements¶
- Python ≥ 3.10. A system Python 3.9 will not work — use a 3.10+ virtual
environment. The easiest way to get one is
uv, which can provision Python 3.12 for direct cloud access. - OS packages: none beyond what the Python wheels provide (no compiler needed).
- For Earth Engine-backed sources: a Google Cloud project and a one-time Earth Engine authentication (see §7). NASA POWER and weather stations need neither.
3. Installation¶
The full steps — GitHub install, Jupyter %pip, and the uv development
setup — are in Getting started → Install. In
short:
# into your own project or notebook:
pip install climate-toolkit
# ...or the latest unreleased code straight from Git:
pip install "git+https://github.com/CGIAR-Climate-Data-Hub/climate-toolkit.git"
# ...or, for development from a clone:
cd climate-toolkit && uv sync
After either, import climate_toolkit works from any directory. Run scripts in
the repo's environment with uv run python my_script.py.
4. Verify the install¶
uv run python -c "import climate_toolkit as ct; print(ct.__version__)"
# Example: 0.2.0
Confirm the public surface:
import climate_toolkit as ct
print([n for n in ct.__all__ if not n.startswith("__")])
# Includes the analysis functions, backend_policy and run_pipeline.
5. Credentials by data source¶
nasa_power(and weather stationsghcn_daily/gsod) use plain HTTPS and need no credentials. Start here.chirps_v3_daily_rnlandchirts_era5support direct cloud access without credentials. On Python 3.12+, runpip install "climate-toolkit[cloud]". Passallow_gee=Falseto exclude Earth Engine fallback.- Earth Engine sources —
era5_land,era_5,chirps_v2(aliaschirps),chirts,imerg,terraclimate,cmip_6,nex_gddp,soil_grid,hwsd— route through Google Earth Engine and require a one-time auth plus a project ID (see §7).
6. Quick start (no credentials)¶
Fetch daily data → DataFrame¶
from datetime import date
import climate_toolkit as ct
from climate_toolkit.fetch_data.source_data.sources.utils.models import ClimateVariable
df = ct.fetch_climate_data(
source="nasa_power",
location_coord=(-1.286, 36.817), # (lat, lon), Nairobi
variables=[ClimateVariable.precipitation,
ClimateVariable.max_temperature,
ClimateVariable.min_temperature],
date_from=date(2020, 1, 1),
date_to=date(2020, 12, 31),
verbose=False,
)
print(df.head())
# date precipitation max_temperature min_temperature
# 0 2020-01-01 0.04 27.17 14.07
# ...
fetch_climate_data returns a pandas DataFrame.
Seasonal statistics → dict¶
stats = ct.analyze_climate_statistics(
location_coord=(-1.286, 36.817),
start_year=2015, end_year=2020,
source="nasa_power",
)
print(stats.keys())
# location, period, source, ..., season_statistics, ltm_season_summary, ...
analyze_climate_statistics returns a nested dict of results. (Use ≥ ~20
years for a real long-term climatology; short windows just print a warning.)
7. Earth Engine setup¶
Sources listed under Earth Engine in §5 need a one-time setup. The full
walkthrough — including the free noncommercial registration path — is in
Getting started → Google Earth Engine credentials.
In brief: run earthengine authenticate, set GCP_PROJECT_ID, then verify with
climate-toolkit gee-check (exits 0 on success).
Once that's done, any function works with EE sources:
# ClimateVariable was imported in the quick-start snippet above.
vars3 = [ClimateVariable.precipitation,
ClimateVariable.max_temperature,
ClimateVariable.min_temperature]
df = ct.fetch_climate_data(
source="era5_land", # Earth Engine
location_coord=(-1.286, 36.817),
variables=vars3,
date_from=date(2020, 1, 1), date_to=date(2020, 12, 31),
)
# NEX-GDDP projections need a model + scenario:
proj = ct.fetch_climate_data(
source="nex_gddp", model="GFDL-ESM4", scenario="ssp245",
location_coord=(-1.286, 36.817),
variables=vars3,
date_from=date(2050, 1, 1), date_to=date(2050, 12, 31),
)
8. Seven analysis functions¶
Every function has a full NumPy-style docstring: help(ct.<function>).
fetch_climate_data¶
ct.fetch_climate_data(
source, location_coord=None, variables=None,
date_from=None, date_to=None, model=None, scenario=None,
stage="preprocessed", cache_dir=None, refresh_cache=False,
sites=None, sites_csv=None, station_id=None, workers=1, verbose=True,
)
stage controls how far the pipeline runs: "raw" →
"transformed" → "preprocessed" (default). Pass sites=/sites_csv= for
multi-site batch fetches (GEE sources and NEX-GDDP).
analyze_climate_statistics¶
ct.analyze_climate_statistics(
location_coord, start_year, end_year, source,
fixed_season=None, crop_name=None,
spei_scale_months=None, spi_scale_months=None,
workers=1, verbose=False,
)
evaluate_hazards¶
ct.evaluate_hazards(
crop_name, location_coord, date_from, date_to, # dates are ISO strings
season_start=None, season_end=None, fixed_season=None,
source="auto", custom_thresholds=None,
soilcp=100.0, soilsat=100.0, workers=1,
)
date_from/date_to are ISO date strings (e.g. "2020-03-01").
compare_climate_periods¶
ct.compare_climate_periods(
location, baseline_start, baseline_end, focal_year, source,
fixed_season=None, crop_name=None, workers=1,
)
compare_climate_sources¶
ct.compare_climate_sources(
sources, lat=None, lon=None, start=None, end=None,
output_dir="./outputs", nex_model=None, nex_scenario="ssp245",
workers=1,
)
sources is
a list, e.g. ["nasa_power", "era5_land"].
download_station_data (keyword-only args)¶
ct.download_station_data(
station_source="ghcn_daily", # or "gsod"
station_coord=(-1.286, 36.817),
date_from=date(2020, 1, 1), date_to=date(2020, 12, 31),
max_distance_km=50.0, auto_select="auto-1",
)
compare_station_to_grids (keyword-only args)¶
ct.compare_station_to_grids(
station_source="ghcn_daily",
station_coord=(-1.286, 36.817),
date_from=date(2020, 1, 1), date_to=date(2020, 12, 31),
grid_sources=["nasa_power", "era5_land"],
)
9. Data sources reference¶
source key |
Data | Earth Engine? |
|---|---|---|
nasa_power |
Daily point climate, 1984– | No |
tamsat |
African rainfall + soil moisture (fragile; optional) | No (direct download) |
ghcn_daily, gsod |
Weather-station observations | No |
era5_land |
ERA5-Land daily aggregates (broad variable set; recommended default) | Yes |
era_5 |
ERA5 daily reanalysis | Yes |
chirps_v2 (alias chirps) |
CHIRPS v2 rainfall | Yes |
chirps_v3_daily_rnl |
CHIRPS v3 daily final rainfall | Optional fallback |
chirts_era5 |
CHIRTS-ERA5 daily Tmax and Tmin | No (cloud extra) |
chirts (deprecated) |
Legacy CHIRTS-daily temperature, 1983–2016 | Yes |
imerg |
GPM IMERG precipitation | Yes |
terraclimate |
Monthly water balance | Yes |
cmip_6 |
GDDP-CMIP6 projections | Yes |
nex_gddp |
NEX-GDDP-CMIP6 projections (needs model + scenario) |
Yes |
soil_grid, hwsd |
Static soil properties | Yes |
Legacy aliases (era5, agera5, nasapower, nexgddp, ghcn, ...) are
normalized automatically.
10. Variables reference¶
variables accepts a list of enum members — the robust form that works on
every version:
from climate_toolkit.fetch_data.source_data.sources.utils.models import ClimateVariable
variables=[ClimateVariable.precipitation,
ClimateVariable.max_temperature,
ClimateVariable.min_temperature]
Recent builds also accept plain strings (e.g. ["precipitation",
"max_temperature"] or the comma string "precipitation,max_temperature"),
matching the CLI. If you hit AttributeError: 'str' object has no attribute
'name', you are on an older build — use the enum form above.
ClimateVariable names: rainfall, precipitation, max_temperature,
min_temperature, mean_temperature, wind_speed, solar_radiation,
humidity, soil_moisture. Soil properties live in SoilVariable.
If you omit variables, each source uses a sensible default set (and drops
variables it doesn't carry — e.g. NASA POWER has no soil moisture).
11. Caching and outputs¶
- Fetches cache under
outputs/cache/<source>/..., keyed by location, date range, and variables. Repeat runs reuse cached frames. - Force a cold fetch:
refresh_cache=True. - Relocate the cache:
cache_dir="/some/stable/path". - Report outputs (from the analysis/compare functions) default to
./outputs.
Both outputs/ and .tmp/ are git-ignored.
12. Recipes¶
One call for the whole workflow: run_pipeline¶
run_pipeline chains fetch → long-term climatology → (optional source
comparison) → seasonal statistics → crop hazards → (optional period comparison)
for one site or many, returning a headline summary table plus every
intermediate result. By default, one failing site does not abort the batch.
import climate_toolkit as ct
# Single site
result = ct.run_pipeline(
name="Nairobi", location_coord=(-1.286, 36.817),
start_year=2019, end_year=2020, source="nasa_power",
fixed_season="03-01:05-31", crop_name="maize",
)
result.summary # one headline row per site (DataFrame)
result.site_results[0].climate_statistics # full nested result, per site
# Many sites (list of dicts, or sites_csv="...", or site_table=DataFrame)
batch = ct.run_pipeline(
sites=[{"name": "A", "lat": -1.0, "lon": 36.0},
{"name": "B", "lat": -2.0, "lon": 37.0}],
start_year=2019, end_year=2020, source="nasa_power",
)
batch.summary # one row per site
batch.errors # per-site failures captured, batch still completes
The long-term climatology defaults to the WMO 1991–2020 baseline
(climatology_baseline=(1991, 2020)). Turn optional steps on with
run_compare_sources=True (+ compare_sources_list=[...]) or
run_compare_periods=True (+ baseline_start/baseline_end/focal_year).
Compare two sources at one site¶
ct.compare_climate_sources(
sources=["nasa_power", "era5_land"], # era5_land needs Earth Engine
lat=-1.286, lon=36.817,
start="2020-01-01", end="2020-12-31",
output_dir="./outputs",
)
Hazard screen for a maize season¶
ct.evaluate_hazards(
crop_name="Maize",
location_coord=(-1.286, 36.817),
date_from="2020-03-01", date_to="2020-08-31",
)
Focal year vs baseline climatology¶
ct.compare_climate_periods(
location=(-1.286, 36.817),
baseline_start=1991, baseline_end=2020,
focal_year=2023,
source="era5_land",
)
Validate a grid product against a nearby station¶
from datetime import date
ct.compare_station_to_grids(
station_source="ghcn_daily",
station_coord=(-1.286, 36.817),
date_from=date(2019, 1, 1), date_to=date(2020, 12, 31),
grid_sources=["nasa_power"],
)
13. Using it in Jupyter / your own project¶
Once installed into your environment (for example, in Jupyter), it's a normal import:
import climate_toolkit as ct
from datetime import date
from climate_toolkit.fetch_data.source_data.sources.utils.models import ClimateVariable
df = ct.fetch_climate_data(
source="nasa_power", location_coord=(-1.286, 36.817),
variables=[ClimateVariable.precipitation],
date_from=date(2022, 1, 1), date_to=date(2022, 3, 31),
)
df.set_index("date")["precipitation"].plot() # plot the daily precipitation series
The import is lightweight (heavy deps load lazily), so notebooks start fast.
14. Troubleshooting¶
| Symptom | Cause / fix |
|---|---|
SyntaxError / package won't import on python3 |
You're on Python 3.9. Use a 3.10+ env (uv sync). |
Earth Engine project ID missing |
Set GCP_PROJECT_ID (see §7). |
Project 'projects/YOUR_PROJECT_ID' not found |
You left the placeholder in — use your real project id. |
| auth refresh / DNS errors on EE sources | Re-run ee.Authenticate(); check network. |
command not recognized: climate-toolkit-* |
Console scripts exist only after uv sync / pip install; or run python -m climate_toolkit.<module>. |
OSError: File name too long on a NASA POWER fetch |
Pass an explicit variables=[...] list instead of relying on the full default set. |
AttributeError: 'str' object has no attribute 'name' on variables= |
Pass enum members (ClimateVariable.*) rather than strings. |
Preflight your Earth Engine setup anytime with:
uv run climate-toolkit gee-check
15. Getting more help¶
help(ct.fetch_climate_data)(or any of the seven functions) for full parameter docs.- The generated API reference and dataset pages on the documentation site
linked from the project's
pyproject.toml/ README. uv run climate-toolkit --helpto see the equivalent CLI subcommands.