Tutorial series: Climate Analysis with GRASS and Python
Chapter 2: GRASS for Climate Data
TipAt a glance
You will build: one year (2015) of daily maximum and minimum temperature (Tmax, Tmin) over Nusa Tenggara Timur (NTT) as two GRASS time series, a daily mean temperature series in degrees Celsius with monthly means, the annual mean and maximum of Tmax, and a map.
You need: Chapter 1 completed (the GRASS project pgca_agera5 and a working .cdsapirc).
Time to run: 540 s (9 minutes) when tested from an empty mapset with the data already downloaded, on Windows 11 with 8 of 80 logical CPUs in use; the one-year download added 452 s. The two slowest cells, the year’s imports and the daily means, take about 2.5 minutes each and are marked below. The checkpoint prints your own time. The preview figures after each step add about 15 s; they were drawn in a later run on the same finished mapset, so the times above leave them out.
Disk: when tested, about 42 MB of downloads and about 10 MB in the GRASS mapset. The checkpoint measures your own.
NoteLearning objectives
After this chapter you can:
Set and inspect the computational region, zoom it to a sub-area without breaking grid alignment, and predict what a coarser resolution does to the values.
Write r.mapcalc expressions that convert units and handle null cells, and limit work to part of the region with a mask.
Build a space-time raster dataset from a year of daily maps and summarise it over time.
Run many independent GRASS module calls in parallel with pygrass, and measure the gain against a serial loop.
Move a small map between GRASS and numpy, and say when that is the right tool.
Setup
Every chapter from here on starts with the same cell. pg.start() runs the steps Chapter 1 taught one by one: it prepares the environment, opens the project, creates this chapter’s mapset ch02 if needed, and sets the region to the active area from config.yml. As in Chapter 1, the pygrass gis and raster modules are imported only after the session has started; importing them earlier failed when this series was tested.
The last lines remove a mask if an interrupted earlier run left one on (masks are explained in section 5).
import datetime as dtimport jsonimport osimport sysimport timefrom pathlib import PathCHAPTER_START = time.time()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 agera5from pgca import session as pgcfg = pg.load_config(ROOT /"config.yml")session = pg.start(cfg, mapset="ch02")import grass.script as gsfrom grass.pygrass.gis.region import Regionfrom grass.pygrass.modules import Module, ParallelModuleQueuefrom grass.pygrass.raster import RasterRowfrom grass.pygrass.raster.abstract import InfoAOI_NAME = cfg["active_aoi"]AOI = cfg["aoi"][AOI_NAME]PROJECT = Path(cfg["paths"]["grassdata"]) / cfg["grass"]["project"]MAPSET = gs.gisenv()["MAPSET"]YEAR =2015VARS = ["tmax", "tmin"]NPROCS =min(8, os.cpu_count() or1)if json.loads(gs.read_command("r.mask.status", format="json"))["present"]: Module("r.mask", flags="r")print("Removed a mask left by an earlier run")print("Mapset:", MAPSET, "| area:", AOI_NAME, AOI, "| parallel processes:", NPROCS)
NPROCS is how many GRASS modules this chapter runs at the same time. It is capped at 8, and the timings quoted in this chapter were measured with 8; lower it if your machine has fewer cores or little memory.
Three small helpers are used throughout:
set_region() sets the region from a box of edges, and refuses a box that is off the AgERA5 grid.
read() reads a map in the current region into a numpy array with pygrass RasterRow. Null cells of floating-point maps become NaN (integer maps would need extra handling; none is read this way here).
set_units() records units and a semantic label (a short name for the variable, explained in section 3) on many maps at once, in this Python process.
import numpy as npdef set_region(box, res=cfg["res"]):if res == cfg["res"]:assert pg.is_grid_aligned(box, res), f"{box} is not on the AgERA5 grid" Module("g.region", n=box["n"], s=box["s"], w=box["w"], e=box["e"], res=res)def read(name): Region().set_raster_region() # see section 4with RasterRow(name) as rr:return np.array([np.array(row, dtype="float64") for row in rr])def set_units(names, units, label):for name in names: info = Info(name, MAPSET) info.units = units info.semantic_label = label
1. Projects, mapsets and the search path
A GRASS project holds data in one coordinate reference system. Inside it, mapsets are separate workspaces: each has its own maps, its own region and its own temporal database, which records the time of each map in a time series (GRASS projects, temporal framework). This series gives every chapter its own mapset, so re-running one chapter cannot overwrite another chapter’s results.
You can only write to the mapset you are in, but you can read any map in the same project by adding @mapset to its name. Unqualified names are looked up along the search path: the current mapset first, then PERMANENT.
print("Mapsets in the project:", gs.read_command("g.mapsets", flags="l", separator="comma").strip())print("Search path: ", gs.read_command("g.mapsets", flags="p", separator="comma").strip())# element="cell" means "look for a raster map"if gs.find_file("tmax_20150701", element="cell", mapset="ch01")["name"]: s = gs.parse_command("r.univar", map="tmax_20150701@ch01", flags="g")print("Read from Chapter 1 without copying: tmax_20150701@ch01 | n", s["n"], "| mean",round(float(s["mean"]), 4), "K")print("Without @ch01 the name is found:", bool(gs.find_file("tmax_20150701", element="cell")["name"]))else:print("tmax_20150701@ch01 not found: run Chapter 1 to see a read across mapsets")
Mapsets in the project: PERMANENT,ch01,ch02
Search path: ch02,PERMANENT
Read from Chapter 1 without copying: tmax_20150701@ch01 | n 1113 | mean 300.3022 K
Without @ch01 the name is found: False
The last line prints False: ch01 is not on the search path, so the bare name is not found.
2. Get one year of data
Chapter 1 downloaded one day. A single CDS request can cover a whole year: list all twelve months and the days 01 to 31, and the CDS skips dates that do not exist. When this chapter was tested, each request returned a zip of about 10.6 MB holding 365 daily NetCDF files, and took 2 min 54 s (Tmin) and 4 min 25 s (Tmax) from acceptance to completion. Expect your times to differ.
cds_request() builds the request (area is north, west, south, east, as before);
download_year() downloads and unzips, skips both if the files are already there, and checks that the zip holds one file per day;
daily_sources() lists, for every day, the GDAL input string and the band to import.
If paths.agera5_archive in config.yml points to a local AgERA5 archive, daily_sources() uses it and nothing is downloaded. The config.yml in the repository points to the author’s archive: set it to null unless you have one (Chapter 1, section 3.1).
The next cell submits two CDS requests (Tmax, then Tmin) under your account, unless the files are already on disk or you use a local archive. When tested, both together took about 7.5 minutes. It prints when each variable is ready.
DL_DIR = pg.check_data_path(cfg["paths"]["downloads"]) /"ch02"DAYS_IN_YEAR = (dt.date(YEAR +1, 1, 1) - dt.date(YEAR, 1, 1)).daysfolders = {}for v in VARS:if agera5.archive_file(cfg, v, YEAR) isnotNone: folders[v] =Noneprint(f"{v}: using the local archive file {agera5.archive_file(cfg, v, YEAR)}")continue t0 = time.time() folders[v] = agera5.download_year(cfg, v, YEAR, AOI_NAME, DL_DIR)print(f"{v}: {len(list(folders[v].glob('*.nc')))} daily files in {folders[v]} ({time.time() - t0:.0f} s)")sources = {v: agera5.daily_sources(cfg, v, YEAR, folders[v]) for v in VARS}for v, s in sources.items():assertlen(s) == DAYS_IN_YEAR, f"{v}: {len(s)} days found, expected {DAYS_IN_YEAR}"print(f"{v}: {len(s)} days, {s[0][0]} to {s[-1][0]}, first input band {s[0][2]}")
tmax: 365 daily files in E:\temp\pgca\downloads\ch02\tmax_2015_ntt (0 s)
tmin: 365 daily files in E:\temp\pgca\downloads\ch02\tmin_2015_ntt (0 s)
tmax: 365 days, 2015-01-01 to 2015-12-31, first input band 1
tmin: 365 days, 2015-01-01 to 2015-12-31, first input band 1
3. Import a year in parallel
Importing a year means 730 r.in.gdal runs, one per variable and day, and none depends on another. pygrass can run such calls side by side (pygrass modules):
Module(..., run_=False) builds a module call without running it.
ParallelModuleQueue(nprocs=N) starts the calls you put() into it, N at a time, and wait() waits for the rest. If a module fails, the queue raises CalledModuleError.
First a comparison on the same 31 days of Tmax: once one after another, once through the queue.
first = sources["tmax"][:31]t0 = time.time()for day, src, band in first: import_day("tmax", day, src, band, run=True)t_serial = time.time() - t0t0 = time.time()queue = ParallelModuleQueue(nprocs=NPROCS)for day, src, band in first: queue.put(import_day("tmax", day, src, band))queue.wait()t_parallel = time.time() - t0print(f"31 days: serial {t_serial:.1f} s | {NPROCS} at a time {t_parallel:.1f} s | "f"{t_serial / t_parallel:.1f} times faster")
31 days: serial 14.6 s | 8 at a time 6.2 s | 2.3 times faster
The gain is well below NPROCS times. Part of the reason is in how the queue works: it starts its modules in batches of NPROCS and waits for the slowest one in a batch before starting the next batch (pygrass source, ParallelModuleQueue.put). The order of the two runs is not the reason: running the parallel pass first gave the same times when tested. The gain also depends on the input: from yearly archive files it was close to 4 times, from these small daily files between 2 and 2.5 times.
The next cell imports the rest of the year for both variables. When tested it took about 2.5 minutes from daily files and 3.5 minutes from a yearly archive, and printed nothing until it finished.
done = {day for day, _, _ in first}t0 = time.time()queue = ParallelModuleQueue(nprocs=NPROCS)for v in VARS:for day, src, band in sources[v]:ifnot (v =="tmax"and day in done): queue.put(import_day(v, day, src, band))queue.wait()print(f"imported in {time.time() - t0:.0f} s")
imported in 144 s
r.in.gdal leaves the units of a new map empty (when tested, r.info reported "none"). set_units() records them, together with a semantic label: a short name for what the map contains (tmax, tmin), stored with the map, which temporal modules can use to pick maps out of a mixed dataset. It writes through the GRASS library in this Python process, which took under a second for hundreds of maps when tested; running r.support once per map does the same job but starts a process each time.
t0 = time.time()for v in VARS: set_units([f"{v}_{d:%Y%m%d}"for d, _, _ in sources[v]], "K", v)info = gs.parse_command("r.info", map=f"tmax_{YEAR}0101", flags="e")print(f"units and labels for {2* DAYS_IN_YEAR} maps in {time.time() - t0:.1f} s | tmax_{YEAR}0101: "f"units {info['units']}, semantic label {info['semantic_label']}")
units and labels for 730 maps in 1.9 s | tmax_20150101: units K, semantic label tmax
Finally, check that every expected map exists. The expected names are built from the list of days, so maps left over from other runs cannot inflate the count.
present = {name.split("@")[0] for name in gs.list_strings("raster", mapset=".")}for v in VARS: expected = {f"{v}_{d:%Y%m%d}"for d, _, _ in sources[v]} missing =sorted(expected - present)print(f"{v}: {len(expected & present)} of {len(expected)} daily maps present", missing[:5] if missing else"")assertnot missing, f"{len(missing)}{v} maps missing: re-run the import cell"
tmax: 365 of 365 daily maps present
tmin: 365 of 365 daily maps present
Look before moving on. A count says the maps exist, not that they hold the right values. The next cell draws three days, the first, one in the middle and the last of the year, for Tmax (top row) and Tmin (bottom row) on one colour scale, using pgca.preview (src/pgca/preview.py), which reads each map in the current region and prints one summary line per map.
A correct import shows the islands with the sea blank (null) in the same cells on every panel, values in kelvin (a few hundred, not a few tens), and every Tmin panel cooler than the Tmax panel above it. A wrong one would show an empty or constant panel, a block of missing land at one edge of the box, or a shifted coastline, which would mean a file was read with the wrong band or the wrong grid.
from pgca import previewPV_DAYS = [f"{YEAR}0101", f"{YEAR}0701", f"{YEAR}1231"]_ = preview.maps([f"{v}_{d}"for v in VARS for d in PV_DAYS], [f"{v}{d}"for v in VARS for d in PV_DAYS], "K", suptitle=f"Imported daily maps, {AOI_NAME}")
tmax 20150101: 2,048 cells, 935 null; min 293.67, mean 300.54, max 302.79 K
tmax 20150701: 2,048 cells, 935 null; min 294.71, mean 300.30, max 304.80 K
tmax 20151231: 2,048 cells, 935 null; min 297.08, mean 302.11, max 305.08 K
tmin 20150101: 2,048 cells, 935 null; min 291.11, mean 298.15, max 301.07 K
tmin 20150701: 2,048 cells, 935 null; min 287.16, mean 296.38, max 300.00 K
tmin 20151231: 2,048 cells, 935 null; min 291.10, mean 298.39, max 301.41 K
Check the printed lines: every map should have the same number of null cells, and the Tmin minimum, mean and maximum should sit below the Tmax ones for the same day.
Two notes for later. pygrass also offers MultiModule, which runs several calls in order within one queue slot; it is not used in this series because in a test on Windows a failing MultiModule left wait() running past a 240 s time limit, while a failing plain Module stops with an error. And GRASS 8.5 ships grass.tools, a newer way to call modules from Python; it is experimental in 8.5 (r.in.gdal manual, Python section), so this series does not build on it.
4. The region in depth
The computational region (extent and resolution) decides which cells most raster modules read and write. GRASS keeps it as mapset state, not as a property of a map. Import modules are the main exception: they read the file cell for cell unless asked to follow the region, which is what -r does in r.in.gdal (raster introduction).
pygrass Region() reads the current region into an object. This chapter reads it with Region() and sets it with the g.region module, the same module you would use on the command line.
reg = Region()print(f"{reg.rows} rows x {reg.cols} cols | n {reg.north} s {reg.south} w {reg.west} e {reg.east} | "f"resolution {reg.nsres:.2f} x {reg.ewres:.2f} degree")
32 rows x 64 cols | n -7.95 s -11.15 w 118.85 e 125.25 | resolution 0.10 x 0.10 degree
Zooming. The sumba box in config.yml covers the western end of the NTT box and is used for a cross-check in a later chapter. Its edges also end in .05 degree, so zooming to it selects a subset of the same cells and nothing is resampled. The try/finally puts the NTT region back even if a step fails.
Sumba region: 13 x 21 cells | aligned: True | n 196 | mean 301.0761 K
Changing the resolution. Before running the next cell, predict: at a resolution of 0.3 degree, will each coarse cell hold the average of the nine 0.1 degree cells it covers?
It will not. On the fly, GRASS gives each region cell the value of the data cell in which the region cell’s centre falls (raster introduction). For an average, r.resamp.stats aggregates the cells explicitly. The box used here is 3.0 by 6.3 degree, a whole number of 0.3 degree cells, and the factor of 3 is odd, so each coarse centre is the centre of one 0.1 degree cell. With an even factor such as 0.2, coarse centres fall on the edges between data cells and the manual calls the result ill-defined.
One detail of read(): RasterRow runs inside this Python process, and the GRASS library keeps the region it had when the process first read a map. g.region runs as a separate process, so read() calls Region().set_raster_region() to pass the current region on; without it, the 0.3 degree read below still returned 32 by 64 cells when tested.
ODD = {"n": -7.95, "s": -10.95, "w": 118.85, "e": 125.15} # 3.0 x 6.3 degreetry: set_region(ODD) fine = read(DAY_MAP) set_region(ODD, res=0.3) coarse = read(DAY_MAP) Module("r.resamp.stats", input=DAY_MAP, output="tmax_avg_0p3", method="average", overwrite=True, quiet=True) avg = read("tmax_avg_0p3")finally: set_region(AOI)centre = fine[1::3, 1::3] # the 0.1 degree cell in the middle of each 3 x 3 blocksame = np.array_equal(np.isnan(coarse), np.isnan(centre)) and np.array_equal(coarse[~np.isnan(coarse)], centre[~np.isnan(centre)])orig = fine[~np.isnan(fine)]print("shape at 0.1:", fine.shape, "| at 0.3:", coarse.shape)print("every 0.3 value equals the 0.1 cell at its block centre:", same)print(f"r.resamp.stats averages equal to some 0.1 value: {np.isin(avg[~np.isnan(avg)], orig).mean():.0%}")print("valid cells at 0.3: on the fly", int((~np.isnan(coarse)).sum()), "| r.resamp.stats", int((~np.isnan(avg)).sum()))
shape at 0.1: (30, 63) | at 0.3: (10, 21)
every 0.3 value equals the 0.1 cell at its block centre: True
r.resamp.stats averages equal to some 0.1 value: 1%
valid cells at 0.3: on the fly 126 | r.resamp.stats 147
Look before moving on. The three arrays from the cell above are still in memory, so the next cell draws them without reading GRASS again: the 0.1 degree data, the 0.3 degree read on the fly, and the 0.3 degree r.resamp.stats average, on one colour scale over the same box. The region is back at NTT by now, which is why the box (ODD) is passed as the extent.
What to look for: the on-the-fly panel is a blocky copy of the data, with small islands and coastal cells dropped wherever a block centre falls on the sea; the averaged panel keeps more coastal blocks and looks smoother: an average of a block can never be warmer than its warmest cell or cooler than its coolest, so its printed maximum is no higher and its minimum no lower than those of the data. The printed lines give the valid-cell counts behind both.
_ = preview.array_maps([fine, coarse, avg], ["data, 0.1 degree", "0.3 degree, on the fly", "0.3 degree, r.resamp.stats"],"K", extent=(ODD["w"], ODD["e"], ODD["s"], ODD["n"]), suptitle=f"{DAY_MAP} at two resolutions")
data, 0.1 degree: 1,890 cells, 806 null; min 293.67, mean 300.53, max 302.79 K
0.3 degree, on the fly: 210 cells, 84 null; min 295.74, mean 300.55, max 302.74 K
0.3 degree, r.resamp.stats: 210 cells, 63 null; min 296.15, mean 300.67, max 302.53 K
On the fly, each coarse cell is a copy of one original cell and the other eight are ignored. r.resamp.stats produced new values. It also ignores null cells by default, so a coastal block with some land cells still gets a value, which is why it has more valid cells; its -n flag makes any null in the block give null. For climate grids, decide which behaviour you want and ask for it explicitly, rather than letting a coarse region decide.
5. Raster algebra with r.mapcalc
r.mapcalc evaluates an expression for every cell of the current region and writes a new map (r.mapcalc). AgERA5 temperatures are in kelvin (the files’ units attribute is K). The conversion to degrees Celsius is its own named step, and the new map gets its own units.
float(...) keeps the result in single precision, like the input. Without it, subtracting a decimal number such as 273.15 produces a double-precision map, twice the size, when tested.
Module("r.mapcalc", expression=f"tmax_c_{DAY} = float(tmax_{DAY} - 273.15)", overwrite=True)Module("r.mapcalc", expression=f"tmean_c_{DAY} = float((tmax_{DAY} + tmin_{DAY}) / 2 - 273.15)", overwrite=True)set_units([f"tmax_c_{DAY}"], "degC", "tmax")set_units([f"tmean_c_{DAY}"], "degC", "tmean")for m in (f"tmax_{DAY}", f"tmax_c_{DAY}", f"tmean_c_{DAY}"): s = gs.parse_command("r.univar", map=m, flags="g") i = gs.parse_command("r.info", map=m, flags="g") units = gs.parse_command("r.info", map=m, flags="e")["units"]print(f"{m:18s}{units:5s}{i['datatype']} n {s['n']:>5} null {s['null_cells']:>4} mean {float(s['mean']):8.3f}")
tmax_20150101 K FCELL n 1113 null 935 mean 300.538
tmax_c_20150101 degC FCELL n 1113 null 935 mean 27.388
tmean_c_20150101 degC FCELL n 1113 null 935 mean 26.193
Look before moving on. The next cell draws the two new maps in degrees Celsius on one colour scale. A correct conversion keeps the same islands and the same blank sea as the kelvin map, with values of a few tens of degrees Celsius; values near 300 would mean the subtraction did not happen, and values below zero over tropical land would mean 273.15 was subtracted twice. Tmean is the average of Tmax and Tmin, so the Tmean panel should be cooler than the Tmax panel in every land cell.
Tmax 20150101: 2,048 cells, 935 null; min 20.52, mean 27.39, max 29.64 degC
Tmean 20150101: 2,048 cells, 935 null; min 19.26, mean 26.19, max 28.76 degC
Null cells. Cells where AgERA5 has no value are null: 935 of the 2,048 NTT cells, the sea part of the box (the map in section 8 shows the pattern). In r.mapcalc any arithmetic with a null gives null, which is why the converted maps have the same null count as the input. isnull() tests for null, null() creates one, and if(condition, a, b) chooses between values.
Two uses below. The first checks that Tmax and Tmin are null in the same cells: comparing two isnull() results gives 0 or 1, never null, so the sum counts the mismatches. The second shows why filling nulls with zero is a mistake: the zeros enter every statistic.
Module("r.mapcalc", expression=f"null_mismatch = isnull(tmax_{DAY}) != isnull(tmin_{DAY})", overwrite=True)mismatch =int(float(gs.parse_command("r.univar", map="null_mismatch", flags="g")["sum"]))Module("r.mapcalc", expression=f"tmax_zero_filled = if(isnull(tmax_{DAY}), 0, tmax_{DAY})", overwrite=True)zf = gs.parse_command("r.univar", map="tmax_zero_filled", flags="g")print("cells where only one of Tmax, Tmin is null:", mismatch)print(f"zero-filled Tmax: n {zf['n']}, null {zf['null_cells']}, mean {float(zf['mean']):.2f} K")
cells where only one of Tmax, Tmin is null: 0
zero-filled Tmax: n 2048, null 0, mean 163.33 K
Look before moving on. The mismatch count is a single number, and zero is what you want. The zero-filled map is easier to judge as a histogram: the next cell reads the original Tmax map and the zero-filled one and plots their values on shared bins. The original values form one narrow group in the range of real air temperatures in kelvin. The zero-filled map adds a second group at 0 K, one value per sea cell, far from any temperature that can occur; its printed mean is the one from the cell above, pulled down by those zeros. Any statistic computed on such a map is wrong, so keep nulls as nulls.
_ = preview.array_hist({"Tmax": preview.read(DAY_MAP), "Tmax, nulls filled with 0": preview.read("tmax_zero_filled")},"K", bins=60, title=f"{DAY_MAP}: nulls kept and nulls filled with 0")
Tmax: 1,113 values; min 293.67, mean 300.54, max 302.79 K
Tmax, nulls filled with 0: 2,048 values; min 0.00, mean 163.33, max 302.79 K
Masks. The region is always a rectangle. A mask limits modules to some of its cells: while a mask is on, cells outside it read as null. r.mask creates one from a raster map (any non-null cell is inside), r.mask -r removes it, and r.mask.status reports whether one is on (r.mask). A mask stays on until you remove it, so the cell below removes it in finally.
The mask is built from cell coordinates: x() and y() return the centre of the current cell, so the expression keeps the cells whose centres lie inside the Sumba box. Masking to Sumba inside the NTT region should give the same statistics as zooming the region to Sumba (zoom, from section 4).
Module("r.mapcalc", overwrite=True, expression=(f"sumba_mask = if(x() > {SB['w']} && x() < {SB['e']} && y() > {SB['s']} && y() < {SB['n']}, 1, null())"))try: Module("r.mask", raster="sumba_mask", overwrite=True, quiet=True) status = json.loads(gs.read_command("r.mask.status", format="json")) masked = gs.parse_command("r.univar", map=DAY_MAP, flags="g")finally:if json.loads(gs.read_command("r.mask.status", format="json"))["present"]: Module("r.mask", flags="r", quiet=True)print("mask status while on:", status)print(f"NTT region + Sumba mask: n {masked['n']} | mean {float(masked['mean']):.4f} K")print(f"Sumba region, no mask: n {zoom['n']} | mean {float(zoom['mean']):.4f} K")
mask status while on: {'present': True, 'name': 'MASK@ch02', 'is_reclass_of': 'sumba_mask@ch02'}
NTT region + Sumba mask: n 196 | mean 301.0761 K
Sumba region, no mask: n 196 | mean 301.0761 K
Look before moving on. The mask is off again, so the next cell does not turn it back on. It reads sumba_mask and the day’s Tmax and applies the mask in numpy, which shows what modules saw while it was on: the full NTT map on the left, and on the right only the land cells inside the Sumba box, everything else null. If the right panel showed cells outside the box, or no cells at all, the x() / y() expression would be wrong. In the second printed line, the cells minus the nulls should equal the n printed above for the masked statistics.
pv_day = preview.read(DAY_MAP)pv_inside =~np.isnan(preview.read("sumba_mask"))_ = preview.array_maps([pv_day, np.where(pv_inside, pv_day, np.nan)], [f"{DAY_MAP}, no mask", "as seen with sumba_mask on"],"K", extent=preview.region_extent(), ncols=2, panel_width=4.5)
tmax_20150101, no mask: 2,048 cells, 935 null; min 293.67, mean 300.54, max 302.79 K
as seen with sumba_mask on: 2,048 cells, 1,852 null; min 298.18, mean 301.08, max 302.79 K
6. The temporal framework
A space-time raster dataset (STRDS) is a named, ordered list of raster maps, each with a valid time stored in the mapset’s temporal database. Temporal modules (t.*) then work on the whole series at once (temporal framework).
Each daily map is registered with an explicit interval, from the start of its day to the start of the next. The names and intervals go into a text file, one map per line as name|start|end, which t.register reads with file=: one file instead of 365 names on a command line. Each name carries @mapset; the manual notes that fully qualified names register faster, and when tested they were about four times faster than bare names. With timestamps in the file, the increment option and -i flag used in Chapter 1 do not apply (t.register).
semantictype in t.create describes the dataset as a whole (here daily maxima or minima); it is separate from the semantic label on each map.
When tested, the next cell took under a minute.
OUT_DIR = pg.check_data_path(cfg["paths"]["outputs"]) /"ch02"OUT_DIR.mkdir(parents=True, exist_ok=True)SEMANTIC = {"tmax": "max", "tmin": "min"}for v in VARS: strds =f"{v}_{YEAR}" reg_file = OUT_DIR /f"{strds}_register.txt" reg_file.write_text("".join(f"{v}_{d:%Y%m%d}@{MAPSET}|{d}|{d + dt.timedelta(days=1)}\n"for d, _, _ in sources[v])) Module("t.create", output=strds, type="strds", temporaltype="absolute", semantictype=SEMANTIC[v], title=f"AgERA5 {v}{YEAR}", description=f"Daily {v}, {AOI_NAME}, Chapter 2", overwrite=True) t0 = time.time() Module("t.register", input=strds, file=str(reg_file), overwrite=True, quiet=True) i = gs.parse_command("t.info", input=strds, flags="g")print(f"{strds}: {i['number_of_maps']} maps, {i['start_time'].strip(chr(39))} to "f"{i['end_time'].strip(chr(39))}, granularity {i['granularity'].strip(chr(39))} "f"({time.time() - t0:.0f} s)")print("first line of the file:", reg_file.read_text().splitlines()[0])
tmax_2015: 365 maps, 2015-01-01 00:00:00 to 2016-01-01 00:00:00, granularity 1 day (15 s)
tmin_2015: 365 maps, 2015-01-01 00:00:00 to 2016-01-01 00:00:00, granularity 1 day (15 s)
first line of the file: tmin_20150101@ch02|2015-01-01|2015-01-02
Granularity is the time step that fits every interval in the dataset: here 1 day. t.rast.list shows the maps in time order; format="json" returns something Python can read directly, and the min and max columns come from the temporal database.
import pandas as pdlisting = json.loads(gs.read_command("t.rast.list", input=f"tmax_{YEAR}", columns="name,start_time,end_time,min,max", format="json"))pd.DataFrame(listing["data"]).head()
name
start_time
end_time
min
max
0
tmax_20150101
2015-01-01 00:00:00
2015-01-02 00:00:00
293.670013
302.792999
1
tmax_20150102
2015-01-02 00:00:00
2015-01-03 00:00:00
293.779724
303.599915
2
tmax_20150103
2015-01-03 00:00:00
2015-01-04 00:00:00
295.115845
303.702789
3
tmax_20150104
2015-01-04 00:00:00
2015-01-05 00:00:00
293.569672
303.318207
4
tmax_20150105
2015-01-05 00:00:00
2015-01-06 00:00:00
295.777466
304.816986
Algebra over time.t.rast.mapcalc runs an r.mapcalc expression for every time step and registers the results as a new dataset (t.rast.mapcalc). In the expression, a dataset name stands for that dataset’s map at the current time step; maps are matched by equal time by default. Here: daily mean temperature in degrees Celsius for the whole year. nprocs lets the module run its own r.mapcalc calls in parallel, so no queue is needed.
Three things to know, all seen when this chapter was tested:
The new maps are numbered by position (tmean_c_day_001 for the first map, padded to the number of maps), not named by date.
The new maps and dataset copy the semantic label and semantic type of the first input (tmax, max). The cell sets the right units and label on the maps and then runs t.support -m, which reloads map metadata into the temporal database, with semantictype="mean".
Overwriting a registered map does not refresh the temporal database until t.support -m runs.
When tested, the next cell took about 2.5 minutes.
t0 = time.time()Module("t.rast.mapcalc", inputs=[f"tmax_{YEAR}", f"tmin_{YEAR}"], expression=f"float((tmax_{YEAR} + tmin_{YEAR}) / 2 - 273.15)", output=f"tmean_c_{YEAR}", basename="tmean_c_day", nprocs=NPROCS, overwrite=True, quiet=True)# flags="u": names only, no header linetmean_maps = gs.read_command("t.rast.list", input=f"tmean_c_{YEAR}", columns="name", flags="u").split()set_units(tmean_maps, "degC", "tmean")Module("t.support", input=f"tmean_c_{YEAR}", semantictype="mean", flags="m", quiet=True)db = json.loads(gs.read_command("t.rast.list", input=f"tmean_c_{YEAR}", columns="name,semantic_label", format="json"))first_mean =float(gs.parse_command("r.univar", map=tmean_maps[0], flags="g")["mean"])print(f"{len(tmean_maps)} maps, first {tmean_maps[0]} | {time.time() - t0:.0f} s")print("labels in the temporal database:", sorted({r["semantic_label"] for r in db["data"]}),"| dataset semantic type:", gs.parse_command("t.info", input=f"tmean_c_{YEAR}", flags="g")["semantic_type"])print(f"first day mean {first_mean:.3f} degC | the same day from section 5: "f"{float(gs.parse_command('r.univar', map=f'tmean_c_{DAY}', flags='g')['mean']):.3f} degC")
365 maps, first tmean_c_day_001 | 148 s
labels in the temporal database: ['tmean'] | dataset semantic type: mean
first day mean 26.193 degC | the same day from section 5: 26.193 degC
GRASS also has t.rast.algebra, a richer language with temporal operators such as shifting a series in time or comparing neighbouring steps (t.rast.algebra). This series does not use it.
Aggregation over time.t.rast.aggregate groups maps into coarser time steps and summarises each group, here monthly means (t.rast.aggregate). sampling="contains" (the default, written out) takes the daily maps whose intervals lie inside each month, and suffix="gran" names the outputs by month.
file_limit matters on Windows. The work is done by r.series, which by default keeps every input map open; when tested on Windows, that failed with “Too many open files” at the 52nd map. Above file_limit maps, the temporal modules tell r.series to reopen maps as needed instead, which is slower but avoids the limit (r.series). This chapter sets it to 40, below where the failure appeared. On Linux and macOS the operating-system limit is usually higher; 40 still works there, only more slowly.
Look before moving on. The table gives each month’s lowest and highest cell; the maps show where they are. The next cell draws four of the twelve monthly means (January, April, July, October) on one colour scale. Expect the same blank sea as the daily maps, values in degrees Celsius, and the cooler and warmer cells in the same places from month to month, with the whole map shifting cooler or warmer together. The July panel should look the coolest of the four, as its min and max columns in the table say. A month that looks like a copy of another, or a panel with far fewer land cells, would point to the aggregation picking the wrong daily maps.
_ = preview.maps([month_maps[i] for i in (0, 3, 6, 9)], None, "degC", ncols=4, panel_width=3.0, suptitle=f"Monthly mean of daily mean temperature, {YEAR}")
tmean_c_mon_2015_01: 2,048 cells, 935 null; min 20.40, mean 26.49, max 29.06 degC
tmean_c_mon_2015_04: 2,048 cells, 935 null; min 20.03, mean 26.70, max 28.53 degC
tmean_c_mon_2015_07: 2,048 cells, 935 null; min 18.14, mean 25.09, max 27.65 degC
tmean_c_mon_2015_10: 2,048 cells, 935 null; min 20.18, mean 26.30, max 28.13 degC
Summary over the whole series.t.rast.series reduces a dataset to one map per method (t.rast.series). It runs on the kelvin Tmax dataset because these are summaries of the raw daily maxima; the results are converted afterwards. The -t flag leaves the outputs without a time stamp, since they belong to no time series.
Two details: - A pygrass parameter that takes several values needs a Python list. A comma-joined string such as "average,maximum" is rejected. - max_raster gives the position of the maximum in the series, counted from 0 (r.series). Because this series starts on 1 January and has no gaps (section 3 checked that), adding 1 gives the day of the year.
When tested, the next cell took about half a minute.
Module("t.rast.series", input=f"tmax_{YEAR}", method=["average", "maximum", "max_raster"], output=[f"tmax_{YEAR}_mean", f"tmax_{YEAR}_max", f"tmax_{YEAR}_maxpos"], flags="t", file_limit=40, nprocs=NPROCS, overwrite=True, quiet=True)for k in ("mean", "max"): Module("r.mapcalc", expression=f"tmax_{YEAR}_{k}_c = float(tmax_{YEAR}_{k} - 273.15)", overwrite=True) set_units([f"tmax_{YEAR}_{k}_c"], "degC", "tmax")Module("r.mapcalc", expression=f"tmax_{YEAR}_maxday = tmax_{YEAR}_maxpos + 1", overwrite=True)for m in (f"tmax_{YEAR}_mean_c", f"tmax_{YEAR}_max_c", f"tmax_{YEAR}_maxday"): s = gs.parse_command("r.univar", map=m, flags="g")print(f"{m:20s} n {s['n']:>5} min {float(s['min']):7.2f} max {float(s['max']):7.2f} mean {float(s['mean']):7.2f}")
tmax_2015_mean_c n 1113 min 23.73 max 31.86 mean 28.14
tmax_2015_max_c n 1113 min 26.70 max 36.92 mean 30.75
tmax_2015_maxday n 1113 min 8.00 max 360.00 mean 316.03
The day of the hottest Tmax falls late in the year on average; section 7 finds the warmest month per cell from the daily means, which gives a check on this.
Look before moving on. A mean over cells hides where the hottest days fall. The next cell draws tmax_2015_maxday with a cyclic colour scale, on which 1 January and 31 December get nearly the same colour, so a cell whose hottest day is in early January does not look like an outlier next to one in late December. Expect much of the land in the colours of the last months of the year, as the mean day printed above suggests, some cells elsewhere, and the sea blank; the printed line repeats the minimum, mean and maximum day from the cell above. Values outside 1 to 365 would mean the + 1 step or the max_raster output is wrong.
_ = preview.maps([f"tmax_{YEAR}_maxday"], [f"Day of the year of the hottest Tmax, {YEAR}"], "day of year", cmap="twilight", vmin=1, vmax=DAYS_IN_YEAR, panel_width=6, digits=0)
Day of the year of the hottest Tmax, 2015: 2,048 cells, 935 null; min 8, mean 316, max 360 day of year
Statistics through time.t.rast.univar computes area statistics for every map in a dataset and returns a table: here, the NTT land average of daily mean temperature for each day of the year (t.rast.univar). The cell draws that average as a line and prints a summary table of the daily statistics.
Look before moving on. The line should follow the monthly table above: lower in the middle of the year, higher towards its end, with no gaps. A single day about 273 degrees above the rest would be a kelvin map that slipped into the series; a flat stretch of identical values would be one map registered for several days.
import ioimport matplotlib.pyplot as plttext = gs.read_command("t.rast.univar", input=f"tmean_c_{YEAR}", separator="comma", nprocs=NPROCS)uni = pd.read_csv(io.StringIO(text), parse_dates=["start", "end"])fig, ax = plt.subplots(figsize=(9, 3))ax.plot(uni["start"], uni["mean"])ax.set_ylabel("degC")ax.set_title(f"NTT land mean of daily mean temperature, {YEAR} (AgERA5)")plt.show()uni[["mean", "min", "max", "non_null_cells"]].describe().round(2)
mean
min
max
non_null_cells
count
365.00
365.00
365.00
365.0
mean
26.22
19.67
28.58
1113.0
std
0.82
1.12
0.76
0.0
min
24.30
16.96
26.92
1113.0
25%
25.58
18.94
27.92
1113.0
50%
26.29
19.74
28.60
1113.0
75%
26.73
20.32
29.06
1113.0
max
28.29
22.15
30.63
1113.0
non_null_cells is the same on every day, the number of land cells: no mask was on and no day had missing land values. Chapter 7 uses t.rast.accumulate, which builds running sums over a series, to add up daily rainfall (t.rast.accumulate).
7. GRASS and numpy
grass.script.array reads a whole map, in the current region, into a numpy array, and writes an array back as a map (grass.script). One trap: by default, null cells are read as 0, not NaN. Pass null="nan".
default read: NaN 0 | zeros 935
null='nan' read: NaN 935 | zeros 0
An example that is short in numpy: the warmest month of 2015 in each cell. Then the GRASS way, t.rast.series with max_raster on the monthly dataset, and a check that both agree.
t0 = time.time()stack = np.stack([garray.array(m, null="nan") for m in month_maps])t_read = time.time() - t0land =~np.isnan(stack).any(axis=0)warmest = np.full(land.shape, np.nan)warmest[land] = np.argmax(stack[:, land], axis=0) +1# month numberout = garray.array() # no map name: an empty array the size of the regionout[...] = warmestout.write("warmest_month_np", null=np.nan, overwrite=True)Module("t.rast.series", input=f"tmean_c_{YEAR}_monthly", method="max_raster", output="warmest_month_pos", flags="t", overwrite=True, quiet=True)grass_pos = garray.array("warmest_month_pos", null=-1)agree =bool((grass_pos[land] +1== warmest[land]).all())months, n_cells = np.unique(warmest[land].astype(int), return_counts=True)print(f"read {len(month_maps)} maps in {t_read:.1f} s | numpy and GRASS agree on every land cell: {agree}")print("land cells by warmest month:", {int(m): int(n) for m, n inzip(months, n_cells)})
read 12 maps in 7.1 s | numpy and GRASS agree on every land cell: True
land cells by warmest month: {3: 3, 4: 25, 5: 1, 11: 679, 12: 405}
Look before moving on. The counts above say how many cells fall in each month, not where. The next cell draws the numpy result warmest, still in memory, with one colour per month that occurs; since the GRASS map agrees on every land cell, it looks the same. Expect the sea blank and the land split mainly between the last two months of the year, as the counts say; the map shows whether those two months divide the islands into regions or alternate from cell to cell. A map of one single month everywhere, or of month 1 on every sea cell, would mean the NaN handling above went wrong.
import calendar_ = preview.array_maps([warmest], [f"Warmest month of {YEAR} (numpy)"], "month", extent=preview.region_extent(), categories={int(k): calendar.month_abbr[int(k)] for k in months}, cmap="tab10", panel_width=6, digits=0)
Warmest month of 2015 (numpy): 2,048 cells, 935 null; min 3, mean 11, max 12 month
Compare with the mean day of the hottest Tmax in section 6: both point to the end of the year for most land cells.
When to use which:
numpy is convenient for small areas and for operations GRASS has no module for. Each garray read runs a GRASS module and holds the whole map in memory; the cell above prints how long 12 reads took.
GRASS modules process maps row by row without loading them whole (r.mapcalc), several t.* modules take nprocs, and results carry their history, units and time stamps with them (you set the units with set_units() and the times with t.register). For the full 1979-2025 record, 17,167 maps per variable, stay in GRASS.
8. Display
grass.jupyter.Map draws maps with the GRASS display modules and shows the image in the notebook (grass.jupyter). The celsius colour table is meant for degrees Celsius, so it is applied to the converted map, not to the kelvin one. When tested, the first map drawn in a fresh setup took 47 s and later ones about 1 s.
grass.jupyter also has TimeSeriesMap for stepping through a dataset; it is marked experimental and is not used in this series.
Look before moving on. This is the same kind of check as the pgca.preview figures, drawn by GRASS itself. The sea should be blank, the legend in degrees Celsius should span the minimum and maximum printed for tmax_2015_mean_c in section 6, and the colours should come from the celsius table. A legend running to about 300 would mean the kelvin map was drawn.
9. A data check: Tmin against Tmax
Daily minimum temperature should not exceed the daily maximum. The cell below compares them for every land cell and day. When this chapter was tested, Tmin was above Tmax in 11 of 406,245 land cell-days, by at most 0.16 K: six neighbouring cells near 10.4-10.5 S, 120.3-120.5 E on three days in June and July 2015. The same values are in the CDS files and in a local archive copy, so they come from AgERA5, not from the import. The cause is not documented in the sources read for this series.
Small cases like these are a property of the data to know about, not an error to fix here. Tmin above Tmax by more than 0.5 K would be different: it would point to swapped variables or a unit error, and the checkpoint stops on it.
tmax_minus_tmin = np.stack([read(f"tmax_{d:%Y%m%d}") - read(f"tmin_{d:%Y%m%d}") for d, _, _ in sources["tmax"]])bad = np.argwhere(tmax_minus_tmin <0)bad_days =sorted({str(sources["tmax"][t][0]) for t, _, _ in bad})print(f"land cell-days with Tmin above Tmax: {len(bad)} of {int((~np.isnan(tmax_minus_tmin)).sum()):,}, "f"largest excess {-min(np.nanmin(tmax_minus_tmin), 0):.3f} K, on {bad_days}")
land cell-days with Tmin above Tmax: 11 of 406,245, largest excess 0.156 K, on ['2015-06-03', '2015-06-07', '2015-07-14']
Look before moving on. The printed line says how many cell-days and by how much; the next cell shows where, from the array tmax_minus_tmin already in memory, without reading the 730 maps again. The first map counts, per cell, the days with Tmin above Tmax: almost all land should be in the 0 class, with the few other cells together near the location given at the start of this section. The second map is the smallest daily Tmax minus Tmin of the year in each cell, in kelvin: by construction it is negative exactly in the non-zero cells of the first map, and zero or above everywhere else on land. A first map with many non-zero cells spread over the islands, or a second map negative almost everywhere, would point to swapped variables.
pv_land =~np.isnan(tmax_minus_tmin).all(axis=0)pv_above = np.where(pv_land, (tmax_minus_tmin <0).sum(axis=0), np.nan)pv_classes = {int(k): f"{int(k)} day"+ (""if k ==1else"s") for k in np.unique(pv_above[pv_land])}_ = preview.array_maps([pv_above], [f"Days with Tmin above Tmax, {YEAR}"], "days", extent=preview.region_extent(), categories=pv_classes, panel_width=6, digits=0)_ = preview.array_maps([tmax_minus_tmin.min(axis=0)], [f"Smallest daily Tmax - Tmin, {YEAR}"], "K", extent=preview.region_extent(), panel_width=6)
Days with Tmin above Tmax, 2015: 2,048 cells, 935 null; min 0, mean 0, max 2 days
Smallest daily Tmax - Tmin, 2015: 2,048 cells, 935 null; min -0.16, mean 1.46, max 5.02 K
10. Checkpoint
These checks read their facts from GRASS, apart from the Tmin check, which uses section 9. The bounds on the daily means, -50 and 60 degC, are deliberately loose: values near 300 would mean a kelvin map slipped through, and the bounds catch that, not unusual weather.
def folder_mb(path): path = Path(path)returnsum(f.stat().st_size for f in path.rglob("*") if f.is_file()) /1e6if path.exists() else0.0def tinfo(strds):return gs.parse_command("t.info", input=strds, flags="g")reg = Region()days = [dt.date(YEAR, 1, 1) + dt.timedelta(days=i) for i inrange(DAYS_IN_YEAR)]present = {name.split("@")[0] for name in gs.list_strings("raster", mapset=".")}mean_info = tinfo(f"tmean_c_{YEAR}")assert gs.gisenv()["MAPSET"] =="ch02"for v in VARS:assert {f"{v}_{d:%Y%m%d}"for d in days} <= present, f"{v} daily maps missing"assertint(tinfo(f"{v}_{YEAR}")["number_of_maps"]) == DAYS_IN_YEARassertint(mean_info["number_of_maps"]) == DAYS_IN_YEARassertint(tinfo(f"tmean_c_{YEAR}_monthly")["number_of_maps"]) ==12assert gs.parse_command("r.info", map=tmean_maps[0], flags="e")["units"] =="degC"assert-50<float(mean_info["min_min"]) andfloat(mean_info["max_max"]) <60, "daily means do not look like degC"assert np.nanmin(tmax_minus_tmin) >-0.5, "Tmin far above Tmax: swapped variables or a unit error?"np_month, gr_pos = garray.array("warmest_month_np", null="nan"), garray.array("warmest_month_pos", null=-1)assertbool((gr_pos[~np.isnan(np_month)] +1== np_month[~np.isnan(np_month)]).all())assertnot json.loads(gs.read_command("r.mask.status", format="json"))["present"], "a mask is still on"assert (reg.rows, reg.cols) == pg.aoi_cells(AOI, cfg["res"]) and np.allclose( [reg.north, reg.south, reg.west, reg.east], [AOI["n"], AOI["s"], AOI["w"], AOI["e"]]), "region not restored"print("All checks passed.")print(f"Disk used: mapset ch02 {folder_mb(PROJECT /'ch02'):.1f} MB, downloads {folder_mb(DL_DIR):.1f} MB, "f"outputs {folder_mb(OUT_DIR):.2f} MB")print(f"Chapter run time: {time.time() - CHAPTER_START:.0f} s")
All checks passed.
Disk used: mapset ch02 9.1 MB, downloads 42.1 MB, outputs 0.03 MB
Chapter run time: 540 s
Summary
What now exists in mapset ch02:
Daily maps tmax_YYYYMMDD and tmin_YYYYMMDD for 2015, in kelvin with units and semantic labels, registered in the datasets tmax_2015 and tmin_2015.
tmean_c_2015: daily mean temperature in degrees Celsius (maps tmean_c_day_001 to _365), made with t.rast.mapcalc, and tmean_c_2015_monthly, its monthly means (maps tmean_c_mon_2015_01 to _12).
Annual summaries of Tmax: tmax_2015_mean_c, tmax_2015_max_c, tmax_2015_maxday, and the warmest month per cell (warmest_month_np, warmest_month_pos).
Teaching maps from sections 4 and 5 (tmax_avg_0p3, tmax_c_20150101, tmean_c_20150101, null_mismatch, tmax_zero_filled, sumba_mask).
On disk: the downloaded zips and daily files in paths.downloads/ch02 (unless you used a local archive), and the registration files in paths.outputs/ch02.
What you can now do: set and zoom the region without leaving the grid, convert units and handle nulls in r.mapcalc, use a mask, build and summarise a time series, and run imports in parallel.
Chapter 3 applies the import pattern to all six AgERA5 variables for 1979-2025, with quality checks, in one mapset agera5. Later chapters do not read from ch02.
Troubleshooting
Symptom
Cause
Fix
ValueError: The parameter <method>, must be one of ...
several values passed as one comma-joined string
pass a Python list (section 6)
Section 3 reports missing maps
some queued imports failed
re-run the import cell, then sections 3 to 6: re-imported maps need re-registering
Statistics include zeros where the sea should be
garray.array() read nulls as 0
pass null="nan" (section 7)
Results cover only Sumba
a mask was left on
re-run the setup cell, which removes it
A coarse result where you expected 32 by 64 cells
region left at a coarser resolution
set_region(AOI)
A RasterRow read has the wrong shape after g.region
the in-process region was not updated
Region().set_raster_region() before reading (section 4)
Too many open files from t.rast.series or t.rast.aggregate
every input map held open at once
set file_limit below 50 (section 6)
The first gj.Map takes close to a minute
first drawing in a fresh setup
wait; later maps are fast
References
Copernicus Climate Change Service. Agrometeorological indicators from 1979 to present derived from reanalysis (AgERA5). DOI: 10.24381/cds.6c68c9bb