import time
CHAPTER_START = time.time()Chapter 1: Setup and Data Planning
Tutorial series: Climate Analysis with GRASS and Python
Chapter 1: Setup and Data Planning
- You will build: a GRASS 8.5 session driven from Python, a GRASS project for AgERA5 data, a computational region over Nusa Tenggara Timur (NTT) that matches the AgERA5 grid cell for cell, and one day of AgERA5 imported into GRASS and checked against the source file.
- You need: the
climateconda environment (section 2) and an account on the Copernicus Climate Data Store (CDS). The series is written and tested on Windows 11; conda-forge also publishes the GRASS build used here for Linux and macOS. - Time to run: on the author’s machine, 112 s on the CDS download path (62 s of it the download, mostly queue time, which varies) and 34 to 37 s with a local AgERA5 archive. The install is not counted. The checkpoint prints your own time. The preview figures after each step add about 4 s (37 s in all when this edition was run).
- Disk: the checkpoint in section 9 measures the files this chapter writes.
- Earlier chapters needed: none.
Learning objectives
By the end of this chapter you can:
- Install GRASS and the Python stack, and start a GRASS session from Jupyter.
- Explain what a GRASS project, mapset and computational region are, and set a region that lines up with a data grid.
- Write a valid CDS API request for AgERA5 and download a small test sample.
- Estimate data volume and the number of maps before committing to 47 years of data.
- Import one day of NetCDF data into GRASS and show that it matches the source exactly.
1. What this series builds
The series follows one study case from raw data to maps: daily weather from AgERA5 becomes daily reference evapotranspiration (ET0), ET0 becomes the Evaporative Demand Drought Index (EDDI), and EDDI becomes maps and district statistics for drought years in eastern Indonesia.
EDDI describes how unusual the evaporative demand over a time window is, compared with the same window in other years, using rank-based probabilities (Hobbins et al., 2016; EDDI User Guide). High EDDI percentiles mean higher evaporative demand than usual; the drought categories ED0 to ED4 cover the 70th to 100th percentiles.
| Chapter | Step | Main GRASS tools |
|---|---|---|
| 1 | Environment, data access, first import | g.region, r.in.gdal |
| 2 | GRASS for climate data: a primer | region, r.mapcalc, t.* modules, pygrass |
| 3 | Download and import 47 years of daily data | r.in.gdal, t.create, t.register |
| 4 | Reference ET computed in GRASS, checked against AgERA5’s own ET0 | r.mapcalc, t.rast.mapcalc |
| 5 | EDDI | t.rast.aggregate, ranking |
| 6 | Maps, district statistics and exports | grass.jupyter, t.rast.univar, r.out.gdal |
| 7 | Rainy-season onset by two definitions | t.rast.aggregate.ds, t.rast.accumulate, t.rast.accdetect |
Chapter 4 explains why ET0 is computed again in GRASS when AgERA5 already ships one: it teaches raster algebra on real equations, and AgERA5’s ET0 gives an independent check of the result.
Three GRASS ideas carry the whole series:
- The computational region. Every raster operation runs on one grid (extent and resolution) that you set explicitly. Section 6 shows why that matters for AgERA5.
- Space-time raster datasets (STRDS). GRASS keeps a time stamp for each map and has modules that aggregate and compute over time series (temporal framework).
- Modules called from Python. Each GRASS tool is a module. The pygrass library wraps modules as Python objects and can run independent ones in parallel.
2. Install
This series uses one conda environment, called climate, for GRASS, Jupyter and the Python data stack. The file environment.yml in the repository lists the packages.
2.1 Windows (conda-forge, used to write this series)
The GRASS download page lists conda-forge as a source of 64-bit Windows builds. In a Miniforge Prompt, from the repository folder:
conda env create -f environment.yml
One extra step on Windows. The conda-forge GRASS 8.5.0 Windows build needs a file called libomp140.x86_64.dll, Microsoft’s OpenMP runtime, and the package does not include it. Without it, every GRASS module stops with error code 0xC0000135 (“DLL not found”).
Microsoft states that this DLL is not redistributable (MSVC /openmp docs). The workaround used here copies the LLVM OpenMP runtime that conda-forge already installs into the environment, under the expected name. In PowerShell, adjusting the path to your environment:
Copy-Item "$env:USERPROFILE\miniforge3\envs\climate\Library\bin\libomp.dll" "$env:USERPROFILE\miniforge3\envs\climate\Library\bin\libomp140.x86_64.dll"
To undo it, delete libomp140.x86_64.dll. If you install a newer grass build, first check whether it still needs this step.
2.2 Windows alternative: OSGeo4W
The GRASS download page also offers the OSGeo4W installer. In that setup GRASS uses its own Python, and Jupyter has to be installed into that Python (grass.jupyter docs). This series has not been tested with OSGeo4W.
2.3 Linux, macOS and WSL
conda-forge publishes the same grass 8.5.0 package for Linux (64-bit) and macOS (Intel and Apple silicon), so the same command applies: conda env create -f environment.yml. The OpenMP DLL step is specific to the Windows build. Inside WSL, follow the Linux route and use Linux-style paths in config.yml. These platforms have not been tested for this series yet.
2.4 Open this notebook with the right kernel
Start Jupyter from the activated environment so the kernel uses its Python:
conda activate climate
jupyter lab
If you start Jupyter some other way (for example from an editor), register the environment once with python -m ipykernel install --user --name climate from the activated environment, then pick the climate kernel. The next cell shows which Python is running.
import platform
import sys
print("Python:", sys.version.split()[0])
print("Interpreter:", sys.executable)
print("OS:", platform.system(), platform.release())Python: 3.14.10
Interpreter: C:\Users\benny\miniforge3\envs\climate\python.exe
OS: Windows 11
3. Start GRASS from Python
GRASS is a set of programs (modules) plus Python packages that call them. A Python process has to be told where GRASS is and which database to work in. This section does it step by step so you can see each part. Later chapters do the same with one call to pgca.session.start().
3.1 Edit and load the settings
Every chapter reads config.yml: data folders, areas of interest, the study period and the AgERA5 variable names. Before running the next cell, open config.yml and edit the paths section for your machine:
grassdata,downloadsandoutputsmust be absolute paths on a local disk, outside any cloud-synced folder such as OneDrive. On Windows the Documents folder is often synced, so a folder such asC:/grassdatais a safer choice. On Linux or macOS use something like/home/you/grassdata.agera5_archivepoints to a folder of yearly AgERA5 files that you already have (layout{variable}/agera5_{variable}_{year}.nc). Most readers do not have one: set it tonull, and this chapter uses the CDS test download instead.
The cell checks the paths and stops with a message if one is unsuitable.
from pathlib import Path
# Find the repository root (the folder that holds config.yml) and make src/ importable.
ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / "config.yml").exists())
sys.path.insert(0, str(ROOT / "src"))
from pgca import session as pg
cfg = pg.load_config(ROOT / "config.yml")
for key in ("grassdata", "downloads", "outputs"):
pg.check_data_path(cfg["paths"][key]) # absolute, not in OneDrive
AOI_NAME = cfg["active_aoi"]
AOI = cfg["aoi"][AOI_NAME]
print("Repository:", ROOT)
print("Active area:", AOI_NAME, AOI)
for k, v in cfg["paths"].items():
print(f"{k:15s} {v}")Repository: C:\Users\benny\OneDrive\Documents\Github\pygrass-climate-analysis
Active area: ntt {'n': -7.95, 's': -11.15, 'w': 118.85, 'e': 125.25}
grassdata E:/grassdata
downloads E:/temp/pgca/downloads
outputs E:/temp/pgca/outputs
staged E:/temp/pgca/staged
agera5_archive E:/temp/agera5
3.2 Prepare the process environment
When you start Python through conda activate climate, conda sets several variables for you. A Jupyter kernel or an editor often starts the interpreter directly, without activation. On Windows that caused three failures while this series was written:
- GRASS modules could not find their DLLs, because the environment’s
Library\binfolder was not onPATH. - Temporal modules failed with
Could not load grass_rasterwhile another conda installation (the base Miniforge) was on the systemPATH. Removing those entries fixed it; which of its libraries conflicted was not traced. - GDAL could not open NetCDF files, because its plugin folder (
GDAL_DRIVER_PATH) was not set.
pg.prepare_env() fixes all three for this Python process only: it puts the environment’s folders first, removes other conda installations from PATH, and points the GDAL and PROJ variables at this environment. On Linux and macOS it does nothing.
dropped = pg.prepare_env()
print("PATH entries removed (other conda installs):", dropped or "none")
from osgeo import gdal
print("GDAL", gdal.__version__, "| netCDF driver available:", gdal.GetDriverByName("netCDF") is not None)PATH entries removed (other conda installs): ['C:\\Users\\benny\\miniforge3', 'C:\\Users\\benny\\miniforge3\\Library\\bin']
GDAL 3.12.3 | netCDF driver available: True
3.3 Find GRASS and its Python packages
grass --config python_path prints the folder that holds the grass Python package. Adding it to sys.path makes grass.script and grass.jupyter importable.
GRASS_EXE = pg.find_grass()
GRASS_PY = pg.add_grass_python(GRASS_EXE)
print("GRASS launcher:", GRASS_EXE)
print("GRASS Python packages:", GRASS_PY)
import grass.jupyter as gj
import grass.script as gsGRASS launcher: C:\Users\benny\miniforge3\envs\climate\Library\bin\grass.BAT
GRASS Python packages: C:\Users\benny\miniforge3\envs\climate\Library\lib\grass85\etc\python
3.4 Create a project
GRASS stores data in a folder tree:
- the GRASS database is a plain folder (
paths.grassdatainconfig.yml); - a project inside it has one coordinate reference system for all of its maps;
- a mapset inside the project is a workspace. Every project has a
PERMANENTmapset, and this series adds one mapset per chapter.
Older material calls a project a location; GRASS has deprecated that name (GRASS projects).
The AgERA5 files declare WGS 84 latitude and longitude (EPSG:4326) in their crs variable, so the project uses EPSG:4326 and no reprojection is needed. pg.ensure_project() creates the project only if it does not exist yet, and checks afterwards that it really was created.
GRASSDATA = pg.check_data_path(cfg["paths"]["grassdata"])
PROJECT = GRASSDATA / cfg["grass"]["project"]
created = pg.ensure_project(PROJECT, cfg["grass"]["epsg"])
print("Created project:" if created else "Project already exists:", PROJECT)Project already exists: E:\grassdata\pgca_agera5
3.5 Create the chapter mapset and start the session
pg.ensure_mapset() creates the ch01 mapset as plain folders, without starting GRASS. gj.init() then starts a GRASS session inside this Python process, working in that mapset. Keeping each chapter in its own mapset stops its maps from mixing with other chapters.
pg.ensure_mapset(PROJECT, "ch01")
session = gj.init(PROJECT / "ch01", grass_path=GRASS_EXE)
env = gs.gisenv()
print("GRASS", gs.version()["version"])
print("Database:", env["GISDBASE"])
print("Project: ", env["LOCATION_NAME"])
print("Mapset: ", env["MAPSET"])
print("CRS: ", gs.parse_command("g.proj", flags="g").get("srid"))GRASS 8.5.0
Database: E:\grassdata
Project: pgca_agera5
Mapset: ch01
CRS: EPSG:4326
3.6 Import pygrass after the session starts
The pygrass modules that read rasters and regions load GRASS’s C libraries when they are imported. In testing they failed with Could not load grass_gis when imported before gj.init(), and worked after it. Import them here, not at the top of the notebook.
This series uses two ways to call a GRASS module, and both run the same programs:
Module("g.region", ...)from pygrass runs a module as a Python object; Chapter 2 uses the same object to queue modules in parallel.gs.run_command(...)andgs.parse_command(...)fromgrass.scriptrun a module once;parse_commandalso turns its text output into a Python dictionary.
from grass.pygrass.gis.region import Region
from grass.pygrass.modules import Module
from grass.pygrass.raster import RasterRow
reg = Region()
print(f"Current region (the mapset default for now): {reg.rows} rows x {reg.cols} cols")Current region (the mapset default for now): 32 rows x 64 cols
Sections 3.2 to 3.5, plus setting the region from config.yml, are what pg.start(cfg, mapset="ch01") does in later chapters. You still import pygrass after it.
4. AgERA5
AgERA5 is a daily dataset of surface weather variables for agriculture, derived from the ERA5 reanalysis and published by the Copernicus Climate Change Service (dataset page, DOI 10.24381/cds.6c68c9bb, CC-BY licence). Facts that matter for this series, from the dataset page and the product user guide:
- Grid: 0.1 by 0.1 degree, regular latitude and longitude, global, daily, from 1979.
- Versions: the dataset page offers 1.1 and 2.0. Version 2.0 (May 2025) added Penman-Monteith reference evapotranspiration, daily minimum and maximum relative humidity, vapour pressure deficit at maximum temperature, and precipitation duration fraction. This series uses 2.0.
- Day boundary: values are aggregated to the local day, not the UTC day. The product user guide notes mismatches of 2 to 3 hours in parts of Asia.
- Latency: the source ERA5 data arrive about one week after real time.
- Reference ET: AgERA5 computes ET0 with the FAO-56 Penman-Monteith method.
- Known issues: version 2.0 has a wind speed artefact at some high-elevation grid points; check wind over mountains before trusting ET0 there.
The table below lists the variables this series uses, as recorded in config.yml: the name you send to the CDS, the statistic, and the variable name inside the NetCDF file you get back.
import pandas as pd
var_table = pd.DataFrame(cfg["agera5"]["variables"]).T[["cds", "statistic", "nc"]].fillna("(none)")
var_table.index.name = "short name"
var_table| cds | statistic | nc | |
|---|---|---|---|
| short name | |||
| tmax | 2m_temperature | 24_hour_maximum | Temperature_Air_2m_Max_24h |
| tmin | 2m_temperature | 24_hour_minimum | Temperature_Air_2m_Min_24h |
| tdew | 2m_dewpoint_temperature | 24_hour_mean | Dew_Point_Temperature_2m_Mean_24h |
| ws10 | 10m_wind_speed | 24_hour_mean | Wind_Speed_10m_Mean_24h |
| srad | solar_radiation_flux | (none) | Solar_Radiation_Flux |
| et0 | reference_evapotranspiration | (none) | ReferenceET_PenmanMonteith_FAO56 |
5. Access the Climate Data Store
5.1 Account and API key
- Register at the CDS and log in.
- Open the AgERA5 dataset page and accept its licence on the Download tab. API requests fail until you do.
- Copy your personal access token from the API how-to page.
- Create a text file called
.cdsapircin your home folder (C:\Users\<you>on Windows) with exactly two lines:
url: https://cds.climate.copernicus.eu/api
key: <your-personal-access-token>
The key line holds the token alone, with nothing in front of it. The API client needs cdsapi 0.7.7 or later. Write the file by hand rather than from a notebook cell, so the token never ends up in a saved notebook.
The next cell checks the file without printing your token. It checks the format only; section 5.3 shows whether the CDS accepts the token.
import importlib.metadata
rc = Path.home() / ".cdsapirc"
lines = rc.read_text().splitlines() if rc.exists() else []
url_ok = any(l.strip() == "url: https://cds.climate.copernicus.eu/api" for l in lines)
key_line = next((l for l in lines if l.startswith("key:")), "")
key_ok = bool(key_line[4:].strip()) and ":" not in key_line[4:]
CDS_READY = rc.exists() and url_ok and key_ok
print(".cdsapirc found:", rc.exists())
print("url line correct:", url_ok)
print("key line in token format:", key_ok)
print("cdsapi version:", importlib.metadata.version("cdsapi")).cdsapirc found: True
url line correct: True
key line in token format: True
cdsapi version: 0.7.7
5.2 Ask the CDS which requests are valid
You do not have to guess request keywords. The CDS publishes each dataset’s request form as JSON, and a constraints endpoint says which combinations are allowed. The next cell asks, for every variable in config.yml, which statistics version 2.0 accepts. Neither call needs your key.
import json
import urllib.request
API = "https://cds.climate.copernicus.eu/api/retrieve/v1/processes/" + cfg["agera5"]["dataset"]
with urllib.request.urlopen(API, timeout=60) as r:
form = json.load(r)
print("Request inputs:", list(form["inputs"]))
print("area default:", form["inputs"]["area"]["schema"].get("default"))
def allowed(variable):
body = json.dumps({"inputs": {"variable": variable, "version": cfg["agera5"]["version"]}}).encode()
req = urllib.request.Request(API + "/constraints", data=body,
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=60) as r:
c = json.load(r)
return {"allowed statistics": ", ".join(c.get("statistic") or []) or "(none)",
"years": f'{min(c["year"])}-{max(c["year"])}'}
rows = {}
for short, spec in cfg["agera5"]["variables"].items():
rows[short] = {"cds variable": spec["cds"], "config statistic": spec["statistic"] or "(none)",
**allowed(spec["cds"])}
pd.set_option("display.max_colwidth", None)
pd.DataFrame(rows).TRequest inputs: ['variable', 'statistic', 'year', 'month', 'day', 'time', 'version', 'area']
area default: [90, -180, -90, 180]
| cds variable | config statistic | allowed statistics | years | |
|---|---|---|---|---|
| tmax | 2m_temperature | 24_hour_maximum | 24_hour_maximum, 24_hour_mean, 24_hour_minimum, day_time_maximum, day_time_mean, night_time_mean, night_time_minimum | 1979-2026 |
| tmin | 2m_temperature | 24_hour_minimum | 24_hour_maximum, 24_hour_mean, 24_hour_minimum, day_time_maximum, day_time_mean, night_time_mean, night_time_minimum | 1979-2026 |
| tdew | 2m_dewpoint_temperature | 24_hour_mean | 24_hour_mean | 1979-2026 |
| ws10 | 10m_wind_speed | 24_hour_mean | 24_hour_mean | 1979-2026 |
| srad | solar_radiation_flux | (none) | (none) | 1979-2026 |
| et0 | reference_evapotranspiration | (none) | (none) | 1979-2026 |
Check that each config statistic appears in the allowed list. Dew point and wind accept only the 24-hour mean; solar radiation and reference ET take no statistic at all.
5.3 Download a test sample
One variable (daily maximum temperature), one day, over the NTT area. Any date works; this one is reused in section 8. The area list is ordered north, west, south, east. The cell skips the download if the file is already there, and writes to paths.downloads, outside the repository.
Set RUN_DOWNLOAD = False only if you set agera5_archive in config.yml and want to work from that archive alone.
import cdsapi
RUN_DOWNLOAD = True
DL_DIR = pg.check_data_path(cfg["paths"]["downloads"]) / "ch01"
DL_DIR.mkdir(parents=True, exist_ok=True)
test_target = DL_DIR / f"agera5_tmax_20150701_{AOI_NAME}.download"
request = {
"variable": "2m_temperature",
"statistic": ["24_hour_maximum"],
"year": ["2015"],
"month": ["07"],
"day": ["01"],
"version": cfg["agera5"]["version"],
"area": [AOI["n"], AOI["w"], AOI["s"], AOI["e"]],
}
print(json.dumps(request))
if RUN_DOWNLOAD and not test_target.exists():
assert CDS_READY, "Fix .cdsapirc first (section 5.1)"
t0 = time.time()
cdsapi.Client().retrieve(cfg["agera5"]["dataset"], request, str(test_target))
print(f"Downloaded in {time.time() - t0:.0f} s"){"variable": "2m_temperature", "statistic": ["24_hour_maximum"], "year": ["2015"], "month": ["07"], "day": ["01"], "version": "2_0", "area": [-7.95, 118.85, -11.15, 125.25]}
When this chapter was tested, the CDS delivered a zip archive of 28,980 bytes holding one NetCDF file. The next cell unzips it, and also accepts a plain NetCDF file in case the delivery format changes. It prints what arrived.
import zipfile
TEST_NC = None
if test_target.exists():
print("Delivered:", test_target.name, f"{test_target.stat().st_size:,} bytes")
if zipfile.is_zipfile(test_target):
with zipfile.ZipFile(test_target) as z:
print("Archive contents:", z.namelist())
z.extractall(DL_DIR)
TEST_NC = DL_DIR / z.namelist()[0]
else:
TEST_NC = test_target
print("Test NetCDF:", TEST_NC)Delivered: agera5_tmax_20150701_ntt.download 28,980 bytes
Archive contents: ['Temperature-Air-2m_Max-24h_C3S-glob-agric_AgERA5_20150701_final-v2.0.0.area-subset.-7.95.125.25.-11.15.118.85.nc']
Test NetCDF: E:\temp\pgca\downloads\ch01\Temperature-Air-2m_Max-24h_C3S-glob-agric_AgERA5_20150701_final-v2.0.0.area-subset.-7.95.125.25.-11.15.118.85.nc
5.4 Look inside the file
Open the file with xarray before importing anything. Check the variable name, the units, the grid size and the coordinates. When this chapter was tested, the file held 32 by 64 cells: exactly the NTT area, so area crops on the server. A grid of 1801 by 3600 would mean you received the whole globe. If you set a local archive, its yearly file for the same variable is shown as well.
spec = cfg["agera5"]["variables"]["tmax"]
ARCHIVE = cfg["paths"].get("agera5_archive")
archive_file = None
if ARCHIVE:
archive_file = Path(ARCHIVE) / spec["archive"] / f"agera5_{spec['archive']}_2015.nc"
if not archive_file.exists():
archive_file = None
print("Archive file:", archive_file)Archive file: E:\temp\agera5\t2mmax\agera5_t2mmax_2015.nc
The next cell opens each file with xarray and prints, for the Tmax variable, its dimensions, its units attribute, and the first and last cell centres along latitude and longitude. Opening a file this way reads only its header and coordinates, not the data.
import numpy as np
import xarray as xr
def describe(path):
with xr.open_dataset(path) as ds:
da = ds[spec["nc"]]
lat, lon = ds["lat"].values, ds["lon"].values
return {
"file": Path(path).name,
"dims": dict(da.sizes),
"units": da.attrs.get("units"),
"lat first/last": (float(lat[0]), float(lat[-1])),
"lon first/last": (float(lon[0]), float(lon[-1])),
"lat step": float(lat[1] - lat[0]) if lat.size > 1 else None,
}
for p in [TEST_NC, archive_file]:
if p is not None:
for k, v in describe(p).items():
print(f"{k:15s} {v}")
print()file Temperature-Air-2m_Max-24h_C3S-glob-agric_AgERA5_20150701_final-v2.0.0.area-subset.-7.95.125.25.-11.15.118.85.nc
dims {'time': 1, 'lat': 32, 'lon': 64}
units K
lat first/last (-7.999999999994429, -11.099999999994253)
lon first/last (118.89999999998304, 125.19999999998265)
lat step -0.09999999999999432
file agera5_t2mmax_2015.nc
dims {'time': 365, 'lat': 1801, 'lon': 3600}
units K
lat first/last (90.0, -89.99999999998977)
lon first/last (-180.0, 179.8999999999795)
lat step -0.09999999999999432
Look before moving on. Draw the variable before you import it. The islands of NTT should show values and the sea should be empty, because AgERA5 has values only over land and xarray turns the file’s fill value into NaN (counted as null in the printed line). The values are daily maximum air temperatures in kelvin (subtract 273.15 for degrees Celsius), so they should read as warm-day temperatures, not values near 0 K or in the thousands. An empty plot, values over the sea, or a coastline far larger than the area you requested would mean the wrong variable, the wrong file or the whole globe. An archive file is cut to the NTT area here so you can compare it with the test download.
import matplotlib.pyplot as plt
from pgca import preview
def day_on_file_grid(path, when="2015-07-01", box=None):
"""One day of the Tmax variable as an array (north at the top) and its extent in degrees."""
with xr.open_dataset(path) as ds:
da = ds[spec["nc"]].sel(time=np.datetime64(when), method="nearest")
lat, lon = ds["lat"].values, ds["lon"].values
iy, ix = np.arange(lat.size), np.arange(lon.size)
if box is not None: # keep only the cells whose centres fall inside the box
iy = np.flatnonzero((lat < box["n"]) & (lat > box["s"]))
ix = np.flatnonzero((lon > box["w"]) & (lon < box["e"]))
a = da.isel(lat=iy, lon=ix).values.astype("float64")
lat, lon, date = lat[iy], lon[ix], str(da["time"].values)[:10]
if lat[0] < lat[-1]: # imshow draws row 0 at the top
a, lat = a[::-1], lat[::-1]
half = cfg["res"] / 2
return a, (lon.min() - half, lon.max() + half, lat.min() - half, lat.max() + half), date
for p, label, box in [(TEST_NC, "test download", None), (archive_file, "archive file, NTT area", AOI)]:
if p is not None:
a, extent, date = day_on_file_grid(p, box=box)
print(f"{label}: {date}, {a.shape[0]} x {a.shape[1]} cells")
_ = preview.array_maps([a], [f"Tmax {date}, {label}"], "K", extent=extent)test download: 2015-07-01, 32 x 64 cells

Tmax 2015-07-01, test download: 2,048 cells, 935 null; min 294.71, mean 300.30, max 304.80 K
archive file, NTT area: 2015-07-01, 32 x 64 cells

Tmax 2015-07-01, archive file, NTT area: 2,048 cells, 935 null; min 294.71, mean 300.30, max 304.80 K
Two details in the description printed before the map come back later:
- The cell centres sit on multiples of 0.1 degree. Section 6 uses that to place the region.
- The coordinate step is not exactly 0.1 in the stored file (
lat stepshows the rounding). When this series was written, selecting the NTT area with float ranges such aslat=slice(-8.0, -11.1)returned 31 by 63 cells instead of 32 by 64. Section 8 selects cells by nearest centre instead.
6. Line up the computational region with the AgERA5 grid
GRASS computes every raster result on the current computational region: its extent (north, south, west, east edges) and its resolution. Maps whose cells do not line up with the region are resampled on the fly, always by nearest neighbour; other methods need an explicit r.resamp.* step (raster introduction).
AgERA5 cell centres sit on multiples of 0.1 degree, so cell edges sit at x.x5. A region with edges on whole degrees, such as north 10, south -10, is half a cell off: every region cell centre falls on a boundary between data cells. The areas in config.yml use edges that end in .05. pg.is_grid_aligned() checks that.
draft_box = {"n": 10, "s": -10, "w": 95, "e": 120} # whole-degree edges
for name, box in {**cfg["aoi"], "whole-degree box": draft_box}.items():
print(f"{name:17s} aligned: {pg.is_grid_aligned(box, cfg['res'])} rows x cols: {pg.aoi_cells(box, cfg['res'])}")ntt aligned: True rows x cols: (32, 64)
sumba aligned: True rows x cols: (13, 21)
indonesia aligned: True rows x cols: (181, 466)
whole-degree box aligned: False rows x cols: (200, 250)
Now set the region to the active area with the g.region module, called through pygrass Module, and read it back with pygrass Region(). The region is a setting of the mapset: it stays in force for every later cell until you change it again.
Module("g.region", n=AOI["n"], s=AOI["s"], w=AOI["w"], e=AOI["e"], res=cfg["res"])
reg = Region()
print(f"Region {AOI_NAME}: {reg.rows} rows x {reg.cols} cols")
print(f"n {reg.north} s {reg.south} w {reg.west} e {reg.east} res {reg.nsres:.4f} x {reg.ewres:.4f}")
print("first cell centre (lat, lon):", round(reg.north - reg.nsres / 2, 3), round(reg.west + reg.ewres / 2, 3))Region ntt: 32 rows x 64 cols
n -7.95 s -11.15 w 118.85 e 125.25 res 0.1000 x 0.1000
first cell centre (lat, lon): -8.0 118.9
The first cell centre lands on a multiple of 0.1, which is where AgERA5 has a value. Section 8 checks that every cell matches.
Look before moving on. The next cell draws the north-west corner of the region you just set, over the AgERA5 cell centres read from the downloaded (or archive) file. The solid lines are the cells of your region; the dashed lines are the same region shifted by half a cell to the north and east, the misaligned case section 8 tests. In the aligned region every dot sits in the middle of a solid cell; in the shifted region the dots sit on the corners of the dashed cells, so each region cell is equally close to four data cells. The printed lines give, over the whole region, the largest distance from a region cell centre to the nearest file cell centre: it should be zero up to floating-point rounding for the aligned region, and half a cell for the shifted one. The cell only draws; it does not change the region.
def corner_drawing(src, k=4):
"""Region cell edges and file cell centres in the k x k cells at the north-west corner."""
with xr.open_dataset(src) as ds:
flat, flon = ds["lat"].values, ds["lon"].values
rlat = reg.north - reg.nsres / 2 - reg.nsres * np.arange(reg.rows) # region cell centres
rlon = reg.west + reg.ewres / 2 + reg.ewres * np.arange(reg.cols)
fig, ax = plt.subplots(figsize=(6.8, 4.5), constrained_layout=True)
for label, shift, style, colour in [("aligned region", 0.0, "-", "0.25"),
("region shifted by half a cell", reg.nsres / 2, "--", "tab:orange")]:
dlat = np.abs((rlat + shift)[:, None] - flat[None, :]).min(axis=1).max()
dlon = np.abs((rlon + shift)[:, None] - flon[None, :]).min(axis=1).max()
print(f"{label}: largest distance to the nearest file cell centre: lat {dlat:.6f}, lon {dlon:.6f} degree")
for i in range(k + 1):
ax.axhline(reg.north + shift - i * reg.nsres, ls=style, color=colour, lw=1)
ax.axvline(reg.west + shift + i * reg.ewres, ls=style, color=colour, lw=1, label=label if i == 0 else None)
x0, x1 = reg.west - 0.75 * reg.ewres, reg.west + k * reg.ewres
y0, y1 = reg.north - k * reg.nsres, reg.north + 0.75 * reg.nsres
gx, gy = np.meshgrid(flon[(flon > x0) & (flon < x1)], flat[(flat > y0) & (flat < y1)])
ax.plot(gx.ravel(), gy.ravel(), "o", color="tab:blue", ms=5, label="AgERA5 cell centres (file)")
ax.set(xlim=(x0, x1), ylim=(y0, y1), xlabel="longitude (degree)", ylabel="latitude (degree)", aspect="equal")
ax.set_title(f"North-west corner of the {AOI_NAME.upper()} region", fontsize=10)
ax.legend(fontsize=7, loc="upper left", bbox_to_anchor=(1.02, 1), frameon=False)
plt.show()
grid_file = TEST_NC if TEST_NC is not None else archive_file
if grid_file is not None:
corner_drawing(grid_file)
else:
print("No AgERA5 file yet: run section 5.3 or set paths.agera5_archive")aligned region: largest distance to the nearest file cell centre: lat 0.000000, lon 0.000000 degree
region shifted by half a cell: largest distance to the nearest file cell centre: lat 0.050000, lon 0.050000 degree

7. Plan data volume and map count
Every number in this section is computed from config.yml or measured on disk.
- Analysis size grows with the area: cells in the area, times days, times 4 bytes per value. The table shows uncompressed sizes; GRASS compresses rasters on disk, and the sea cells (null in AgERA5) compress well.
- Download size follows the area, because
areacrops on the server (section 5.4): one day of one variable over NTT came to 28,980 bytes. A yearly file of the whole globe from a local archive is about 2.5 GB per variable. - Number of maps. GRASS stores each day as its own raster map, so a long daily record means many maps.
The period ends on 31 December 2025 because 2026 was still incomplete when this series was written.
import datetime as dt
start = dt.date.fromisoformat(cfg["period"]["start"])
end = dt.date.fromisoformat(cfg["period"]["end"])
n_days = (end - start).days + 1
n_vars = len(cfg["agera5"]["variables"])
plan = {}
for name, box in cfg["aoi"].items():
rows, cols = pg.aoi_cells(box, cfg["res"])
per_var_gb = rows * cols * 4 * n_days / 1e9
plan[name] = {"cells": rows * cols,
"GB per variable (uncompressed)": round(per_var_gb, 2),
f"GB for {n_vars} variables (uncompressed)": round(per_var_gb * n_vars, 2)}
print(f"Period {start} to {end}: {n_days:,} days, so {n_days:,} maps per variable and {n_days * n_vars:,} maps in total")
plan_table = pd.DataFrame(plan).T
plan_table["cells"] = plan_table["cells"].astype(int)
plan_tablePeriod 1979-01-01 to 2025-12-31: 17,167 days, so 17,167 maps per variable and 103,002 maps in total
| cells | GB per variable (uncompressed) | GB for 6 variables (uncompressed) | |
|---|---|---|---|
| ntt | 2048 | 0.14 | 0.84 |
| sumba | 273 | 0.02 | 0.11 |
| indonesia | 84346 | 5.79 | 34.75 |
The table is computed from config.yml. The next cell measures the files that are actually on disk: the test download and, if you set one, the yearly archive file.
measured = {}
if TEST_NC is not None:
measured["test download: 1 day, 1 variable"] = Path(TEST_NC).stat().st_size
if archive_file is not None:
measured["local archive: 1 year, tmax, global"] = archive_file.stat().st_size
for k, v in measured.items():
print(f"{k:40s} {v / 1e6:10.3f} MB")test download: 1 day, 1 variable 0.029 MB
local archive: 1 year, tmax, global 1960.358 MB
Plan used in this series
| Item | Where | Note |
|---|---|---|
| GRASS database | paths.grassdata |
local disk, outside OneDrive |
| Raw downloads | paths.downloads |
kept until imported and checked |
| Outputs (GeoTIFF, NetCDF, figures) | paths.outputs |
what you share |
Raw imports: one mapset agera5 for all six variables; ET0 and EDDI: one mapset each |
GRASS project | this series’ choice; Chapter 3 explains why one mapset rather than one per variable |
Develop and test on ntt first: importing one day took 1.2 to 1.4 s there in two runs (section 8). Switch active_aoi to indonesia in config.yml only after a chapter works.
8. First import, and proof that it matches the source
r.in.gdal imports raster files through GDAL, here using the netCDF driver checked in section 3.2 (r.in.gdal). With the -r flag it reads only the part of the file that overlaps the current region, which keeps imports from global files small.
Each day is one GDAL band. In a yearly archive file, 1 July 2015 is band 182 (the day of the year). The one-day test download has a single band. The next cell picks the archive if you have one, otherwise the test download.
DAY = dt.date(2015, 7, 1)
if archive_file is not None:
src_path, band = archive_file, (DAY - dt.date(DAY.year, 1, 1)).days + 1
elif TEST_NC is not None:
src_path, band = Path(TEST_NC), 1
else:
raise FileNotFoundError("No AgERA5 file: run section 5.3 or set paths.agera5_archive")
MAP = f"tmax_{DAY:%Y%m%d}"
gdal_name = f'NETCDF:"{src_path.as_posix()}":{spec["nc"]}'
t0 = time.time()
# overwrite=True lets you re-run this cell
Module("r.in.gdal", input=gdal_name, band=band, output=MAP, flags="r", overwrite=True, quiet=True)
print(f"Imported {MAP} from {src_path.name}, band {band}, in {time.time() - t0:.1f} s")
info = gs.raster_info(MAP)
print("Imported map:", info["rows"], "rows x", info["cols"], "cols | n", info["north"], "s", info["south"],
"w", info["west"], "e", info["east"])Imported tmax_20150701 from agera5_t2mmax_2015.nc, band 182, in 1.3 s
Imported map: 33 rows x 65 cols | n -7.95 s -11.25 w 118.85 e 125.35
From the cropped test download the imported map matches the region exactly (32 by 64), because the file stops at the region’s edges. From a yearly archive file it comes out one row and one column larger (33 by 65). GDAL reads the file’s cell size as 0.099999999999994 degree, slightly less than 0.1, so the region’s south and east edges fall a tiny fraction into the next row and column, and -r keeps them. This is harmless: calculations use the region, not the map’s own extent. It is also why later chapters set the region from config.yml, never from an imported map (g.region raster=...).
Look before moving on. Draw the map you just imported, as GRASS sees it in the current region. It should look like the source file in section 5.4: values on the islands, empty sea, and a cell count in the printed line equal to the region’s rows times columns. A map that is entirely null, a strip of null cells along one edge, or islands that look shifted against the section 5.4 plot would point to the wrong band, a region that does not cover the file, or a misaligned region.
_ = preview.maps([MAP], [f"{MAP} in GRASS"], "K")
tmax_20150701 in GRASS: 2,048 cells, 935 null; min 294.71, mean 300.30, max 304.80 K
r.univar prints summary statistics of a map over the current region; flags="g" asks for key=value output that parse_command turns into a dictionary. Its n (valid cells) plus null_cells should equal the cell count in the preview line above, and its minimum, mean and maximum should agree with that line to the digits it shows.
stats = gs.parse_command("r.univar", map=MAP, flags="g")
print({k: stats[k] for k in ("n", "null_cells", "min", "max", "mean")}){'n': '1113', 'null_cells': '935', 'min': '294.713500976562', 'max': '304.804016113281', 'mean': '300.302167126432'}
Now read the same cells directly with xarray and compare. Cells are picked by nearest centre with a tight tolerance; region cells that the file does not cover come back empty and are counted.
lats = np.round(reg.north - reg.nsres / 2 - reg.nsres * np.arange(reg.rows), 2)
lons = np.round(reg.west + reg.ewres / 2 + reg.ewres * np.arange(reg.cols), 2)
with xr.open_dataset(src_path) as ds:
da = ds[spec["nc"]].isel(time=band - 1)
print("xarray date of band:", str(da["time"].values)[:10])
ref_da = da.reindex(lat=lats, lon=lons, method="nearest", tolerance=0.01)
covered = np.isin(lats, ds["lat"].round(2))[:, None] & np.isin(lons, ds["lon"].round(2))[None, :]
ref = ref_da.values.astype("float64")
with RasterRow(MAP) as rr:
grass_vals = np.array([np.array(row, dtype="float64") for row in rr])
same_nulls = bool((np.isnan(grass_vals[covered]) == np.isnan(ref[covered])).all())
max_diff = float(np.nanmax(np.abs(grass_vals[covered] - ref[covered])))
print("region cells:", grass_vals.size, "| covered by the file:", int(covered.sum()))
print("valid cells:", int(np.isfinite(ref).sum()), "| same null pattern:", same_nulls, "| max abs difference:", max_diff)xarray date of band: 2015-07-01
region cells: 2048 | covered by the file: 2048
valid cells: 1113 | same null pattern: True | max abs difference: 0.0
Look before moving on. The next cell draws the two arrays the check compared, on one colour scale, and then their difference on a scale centred on zero. The GRASS map and the source array should be indistinguishable cell for cell, with the same empty sea. The difference should be zero on every land cell, so its printed minimum, mean and maximum all read 0.00 K and the panel is a single neutral colour; when every difference is zero the colour bar range carries no information. A difference that traces the coastline, or a band of non-zero cells along one edge, would mean a half-cell offset or the wrong band.
_ = preview.array_maps([grass_vals, ref], ["GRASS map (RasterRow)", "source file (xarray)"], "K",
extent=preview.region_extent())
_ = preview.array_maps([grass_vals - ref], ["GRASS minus source"], "K", extent=preview.region_extent(),
center=0, cmap="RdBu_r")
GRASS map (RasterRow): 2,048 cells, 935 null; min 294.71, mean 300.30, max 304.80 K
source file (xarray): 2,048 cells, 935 null; min 294.71, mean 300.30, max 304.80 K

GRASS minus source: 2,048 cells, 935 null; min 0.00, mean 0.00, max 0.00 K
Identical values and an identical null pattern show that the region lines up with the grid, that nothing was resampled, and that the band chosen really is 1 July. AgERA5 has values only over land, so sea cells are null.
To see what a misaligned region does, shift the region by half a cell and compare. GRASS now resamples by nearest neighbour, so the statistics change even though the data did not. The exact numbers differ between a cropped download and an archive file, because the shifted region reaches half a cell past the edge of a cropped file. The try/finally puts the aligned region back even if something fails.
try:
Module("g.region", n=AOI["n"] + 0.05, s=AOI["s"] + 0.05, w=AOI["w"] + 0.05, e=AOI["e"] + 0.05,
res=cfg["res"])
shifted = gs.parse_command("r.univar", map=MAP, flags="g")
finally:
Module("g.region", n=AOI["n"], s=AOI["s"], w=AOI["w"], e=AOI["e"], res=cfg["res"])
print(f"aligned region: n={stats['n']:>5} mean={float(stats['mean']):.4f} K")
print(f"shifted region: n={shifted['n']:>5} mean={float(shifted['mean']):.4f} K")aligned region: n= 1113 mean=300.3022 K
shifted region: n= 1136 mean=300.2939 K
Finally, register the map in a space-time raster dataset. Chapter 3 does this for every day of every variable; here it is one map, to check that the temporal framework works. temporaltype="absolute" means real calendar dates, and semantictype says what the values represent (here daily maxima). In t.register, start with increment="1 days" and flags="i" gives the map a validity interval of one day.
STRDS = "tmax_test"
# overwrite=True lets you re-run this cell
Module("t.create", output=STRDS, type="strds", temporaltype="absolute", semantictype="max",
title="AgERA5 Tmax test", description="Chapter 1 test", overwrite=True)
Module("t.register", input=STRDS, maps=MAP, start=DAY.isoformat(), increment="1 days",
flags="i", overwrite=True)
tinfo = gs.parse_command("t.info", input=STRDS, flags="g")
print("STRDS", STRDS, "| maps:", tinfo["number_of_maps"], "| start:", tinfo["start_time"].strip("'"))STRDS tmax_test | maps: 1 | start: 2015-07-01 00:00:00
9. Checkpoint
These checks read the current state from GRASS, so they fail loudly if something the next chapters depend on is missing. The cell also measures the disk space this chapter used.
def folder_mb(path):
path = Path(path)
return sum(f.stat().st_size for f in path.rglob("*") if f.is_file()) / 1e6 if path.exists() else 0.0
env = gs.gisenv()
reg = Region()
rows, cols = pg.aoi_cells(AOI, cfg["res"])
check = gs.parse_command("r.univar", map=MAP, flags="g")
maps_in_strds = int(gs.parse_command("t.info", input=STRDS, flags="g")["number_of_maps"])
assert "onedrive" not in env["GISDBASE"].lower(), "GRASS database is inside OneDrive"
assert env["MAPSET"] == "ch01"
assert (reg.rows, reg.cols) == (rows, cols), "region size does not match config.yml"
assert np.allclose([reg.north, reg.south, reg.west, reg.east],
[AOI["n"], AOI["s"], AOI["w"], AOI["e"]]), "region edges do not match config.yml"
assert int(check["n"]) > 0, "no valid cells in the imported map"
assert same_nulls and max_diff == 0.0, "GRASS and xarray disagree (section 8)"
assert maps_in_strds == 1
print("All checks passed.")
print(f"Disk used: mapset ch01 {folder_mb(PROJECT / 'ch01'):.2f} MB, downloads {folder_mb(DL_DIR):.2f} MB")
print(f"Chapter run time: {time.time() - CHAPTER_START:.0f} s")All checks passed.
Disk used: mapset ch01 0.52 MB, downloads 0.06 MB
Chapter run time: 37 s
Summary
What now exists:
- Environment: the
climateenvironment with GRASS 8.5, started from Python withpg.prepare_env(),gj.init()and pygrass. - GRASS database (
paths.grassdata): projectpgca_agera5(EPSG:4326) with mapsetsPERMANENTandch01. Inch01: the maptmax_20150701and the space-time datasettmax_test. - Downloads (
paths.downloads/ch01): the one-day test file, if you ran section 5.3. - Checked: the
.cdsapircformat, the request keywords against the CDS’s own form, the region against the AgERA5 grid, and the imported values against the source file.
Chapter 2 starts from pg.start(cfg, mapset="ch02"), reuses the same project and region, and covers the region in more depth, raster algebra with r.mapcalc, null values, the temporal framework, and running modules in parallel with pygrass.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
A GRASS module exits with 0xC0000135, or project creation fails (Windows) |
missing libomp140.x86_64.dll |
section 2.1 |
Could not load grass_raster from a t.* module (Windows) |
another conda installation on PATH |
run pg.prepare_env() before importing GRASS (section 3.2) |
Could not load grass_gis when importing pygrass |
pygrass imported before gj.init() |
import it after the session starts (section 3.6) |
r.in.gdal: unable to open datasource on a .nc file |
GDAL netCDF plugin missing or not found | install libgdal-netcdf; run pg.prepare_env() |
ValueError ... not an absolute path or inside OneDrive |
config.yml paths |
section 3.1 |
| CDS request rejected | licence not accepted, or invalid keyword | accept the licence on the dataset page; check section 5.2 |
References
- Copernicus Climate Change Service. Agrometeorological indicators from 1979 to present derived from reanalysis (AgERA5). DOI: 10.24381/cds.6c68c9bb. Product user guide: https://confluence.ecmwf.int/x/3FmaE
- Copernicus Climate Data Store. How to use the CDS API: https://cds.climate.copernicus.eu/how-to-api
- GRASS Development Team. Download and install: https://grass.osgeo.org/download/
- GRASS Development Team. GRASS projects: https://grass.osgeo.org/grass-stable/manuals/grass_projects.html
- GRASS Development Team. Raster introduction: https://grass.osgeo.org/grass-stable/manuals/rasterintro.html
- GRASS Development Team. Temporal framework introduction: https://grass.osgeo.org/grass-stable/manuals/temporalintro.html
- GRASS Development Team. grass.jupyter: https://grass.osgeo.org/grass-stable/manuals/libpython/grass.jupyter.html
- GRASS Development Team. PyGRASS: https://grass.osgeo.org/grass-stable/manuals/libpython/pygrass_index.html
- GRASS Development Team. r.in.gdal: https://grass.osgeo.org/grass-stable/manuals/r.in.gdal.html
- Hobbins, M. T., Wood, A., McEvoy, D. J., Huntington, J. L., Morton, C., Anderson, M., and Hain, C. (2016). The Evaporative Demand Drought Index. Part I: Linking drought evolution to variations in evaporative demand. Journal of Hydrometeorology, 17(6), 1745-1761. DOI: 10.1175/JHM-D-15-0121.1
- Lukas, J., Hobbins, M., Rangwala, I., and the EDDI team (2017). The EDDI User Guide, v1.0. https://psl.noaa.gov/eddi/pdf/EDDI_UserGuide_v1.0.pdf
- Microsoft. /openmp (Enable OpenMP Support): https://learn.microsoft.com/en-us/cpp/build/reference/openmp-enable-openmp-2-0-support