Tutorial series: Climate Analysis with GRASS and Python
Chapter 4: Reference Evapotranspiration in GRASS
TipAt a glance
You will build: an elevation map on the AgERA5 grid from a public DEM; daily ASCE standardized reference evapotranspiration (mm per day) for every day, for two reference crops: short grass (ETos, GRASS time series etos), compared cell by cell with the reference evapotranspiration AgERA5 ships (et0, Chapter 3), and tall alfalfa (ETrs, time series etrs), the one EDDI uses in Chapter 5.
Two sizes: the teaching years 2015 and 2016 by default; with run_full: true in config.yml, 1979-2025. Chapter 5 needs the full record.
You need: Chapter 3 run for at least the same years (the agera5 mapset, and its prepared files in paths.staged), and an internet connection for the DEM tiles (32 MB for NTT when tested). No account is needed.
Time and disk: when tested on Windows 11 with 8 of 80 logical CPUs in use, the teaching years took 209 s and the full record 2,898 s, about 48 minutes, the preview figures included. Of the full run, ETos took 1,016 s to compute and 260 s to register, reading ETos and et0 back for the comparison 727 s, and ETrs 652 s from computing to registering. Times vary between runs: an earlier full run on the same machine computed ETos in 461 s and read the comparison in 158 s. The full record leaves 446,627 files and 317 MB in mapset ch04; the teaching years 35 MB. The outputs shown are from the full run; the checkpoint prints your own time and disk.
NoteLearning objectives
After this chapter you can:
Get a DEM for any area without an account, and bring it to a coarse grid correctly: sea as 0 m, the mean over each cell, edges on the grid.
Write a multi-step physical formula as named r.mapcalc maps with units, then as one expression, and check it against a published worked example.
Run a formula for every day of a long record quickly, and say why the obvious routes are slower.
Compare two products cell by cell and test which settings and inputs explain their differences.
Decide, and state, how a formula treats physically odd inputs.
Setup
This chapter writes into its own mapset, ch04, and reads the AgERA5 inputs from agera5 (Chapter 3). The kernel starts in ch04, because pygrass writes in-process only to the mapset the kernel started in (Chapter 3, section 7). pg.start also sets the region to the area at 0.1 degree, as in Chapter 3; nothing in this chapter changes it. Three lines in the cell set defaults:
GRASS_OVERWRITE=0 undoes the overwrite-everything default of grass.jupyter, as in Chapter 3.
g.mapsets operation=add puts agera5 on the search path, so tmax@agera5 and the temporal datasets there can be read.
g.gisenv set=NPROCS=1 sets how many threads a GRASS tool with an nprocs option uses when you do not set it. Section 5 explains why one is right here. It lasts for this session only.
N_PARALLEL is something else: how many GRASS processes this notebook runs side by side.
import datetime as dtimport jsonimport osimport reimport 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 dem, et0, tgisfrom pgca import session as pgcfg = pg.load_config(ROOT /"config.yml")RAW ="agera5"# inputs from Chapter 3HERE ="ch04"# this chapter's mapssession = pg.start(cfg, mapset=HERE)os.environ["GRASS_OVERWRITE"] ="0"import grass.jupyter as gjimport grass.script as gsimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport xarray as xrfrom grass.pygrass.modules import Module, ParallelModuleQueuefrom grass.pygrass.raster import numpy2raster, raster2numpyfrom grass.pygrass.raster.abstract import Infoif RAW notin gs.parse_command("g.mapsets", flags="p", format="json")["mapsets"]: gs.run_command("g.mapsets", operation="add", mapset=RAW)gs.run_command("g.gisenv", set="NPROCS=1")AOI_NAME = cfg["active_aoi"]AOI = cfg["aoi"][AOI_NAME]PROJECT = Path(cfg["paths"]["grassdata"]) / cfg["grass"]["project"]RUN_FULL =bool(cfg["run_full"])FULL_YEARS =list(range(int(cfg["period"]["start"][:4]), int(cfg["period"]["end"][:4]) +1))TEACH =list(range(cfg["teaching_years"][0], cfg["teaching_years"][1] +1))YEARS = FULL_YEARS if RUN_FULL else TEACHINPUTS = ["tmax", "tmin", "tdew", "ws10", "srad"]NC = {v: spec["nc"] for v, spec in cfg["agera5"]["variables"].items()}N_PARALLEL =min(8, os.cpu_count() or1)STAGED = pg.check_data_path(cfg["paths"]["staged"])DEM_DIR = pg.check_data_path(cfg["paths"]["downloads"]) /"dem"OUT_DIR = pg.check_data_path(cfg["paths"]["outputs"]) /"ch04"(OUT_DIR /"mapcalc").mkdir(parents=True, exist_ok=True)print("Mapset:", gs.gisenv()["MAPSET"], "| search path:", gs.parse_command("g.mapsets", flags="p", format="json")["mapsets"])print("Area:", AOI_NAME, "| years:", YEARS[0], "to", YEARS[-1], "| full run:", RUN_FULL, "| parallel processes:", N_PARALLEL)
inputs_for() gives the five input map names of one day, qualified with their mapset.
done() lists this chapter’s daily maps (<prefix>_YYYYMMDD) that are finished, which section 5 marks by setting units last, as Chapter 3 did.
LAT holds the latitude of each row’s cell centre, for the numpy calculations later.
The check reads the period of every input dataset with one t.list call. The separator is named (pipe) rather than typed as |, which Windows treats as a command-line pipe.
def days_of(year): n = (dt.date(year +1, 1, 1) - dt.date(year, 1, 1)).daysreturn [dt.date(year, 1, 1) + dt.timedelta(days=i) for i inrange(n)]def inputs_for(day):return [f"{v}_{day:%Y%m%d}@{RAW}"for v in INPUTS]def done(prefix, units="mm d-1"): daily = re.compile(rf"^{prefix}_\d{{8}}$") names = [n.split("@")[0] for n in gs.list_strings("raster", pattern=f"{prefix}_*", mapset=HERE)]return {n for n in names if daily.match(n) and Info(n, HERE).units == units}DAYS = [d for y in YEARS for d in days_of(y)]reg = gs.region()LAT = reg["n"] - reg["nsres"] * (np.arange(reg["rows"]) +0.5)listing = gs.read_command("t.list", type="strds", columns="name,start_time,end_time", where=f"mapset = '{RAW}'", separator="pipe")periods = {row.split("|")[0]: row.split("|")[1:] for row in listing.splitlines() if row.count("|") ==2}for v in INPUTS + ["et0"]: first, last = periods[v][0][:10], periods[v][1][:10]assert first <=f"{YEARS[0]}-01-01"and last >=f"{YEARS[-1] +1}-01-01", f"{v}: run Chapter 3 for {YEARS[0]}-{YEARS[-1]}"print(f"Inputs cover the {len(DAYS):,} days of this run; region {reg['rows']} x {reg['cols']} cells.")
Inputs cover the 17,167 days of this run; region 32 x 64 cells.
Reference evapotranspiration is the evapotranspiration of a hypothetical, well-watered grass reference surface under the day’s weather (FAO-56 chapter 2): a measure of how strongly the air draws water from the ground. EDDI, in Chapter 5, ranks it against its own history. AgERA5 already ships it: the et0 dataset of Chapter 3, “Calculated using the Penman-Monteith method as described by the FAO56 guidelines” (AgERA5 overview). The AgERA5 algorithm description (ATBD) says its routines were derived from the PCSE crop-model library, in a vectorised form (ATBD, section 4.5).
Why compute it again:
EDDI is defined on the ASCE standardized equation, which its user guide calls identical to the FAO-56 form at daily time steps (EDDI User Guide, p15). This chapter computes that equation, so Chapter 5 knows exactly what it ranks. NOAA’s EDDI uses its tall reference crop (section 8).
The method becomes yours to change: the reference crop (short grass or tall alfalfa), the limits on odd inputs, the elevation.
Two independent implementations that agree are a check on both, even though they share the AgERA5 inputs. Where they differ, the difference says something about the inputs or the settings.
The ASCE and FAO-56 daily equations share their form and almost every constant. They differ in three details:
Detail
ASCE 2005 (this chapter)
FAO-56
Stefan-Boltzmann constant
4.901e-9 MJ K-4 m-2 d-1 (p19)
4.903e-9
Limits on Rs/Rso, solar radiation relative to its clear-sky value
0.3 to 1.0 (p20)
at most 1.0
Wind at 2 m (u2)
no lower limit stated
“limited to about u2 >= 0.5 m/s”
Sources: ASCE-EWRI 2005, pages as given; FAO-56 chapter 3. The PCSE code AgERA5 derives from applies neither limit, caps the actual vapour pressure at the saturation value, and sets negative results to zero (pcse/util.py, penman_monteith). Whether AgERA5 kept all of that is not stated in its algorithm description. Sections 6 and 7 measure what each choice changes.
2. A DEM on the AgERA5 grid
Elevation enters twice: through atmospheric pressure, and hence the psychrometric constant (the factor linking temperature and vapour pressure in evaporation, ASCE eq 3 and 4), and through clear-sky radiation (eq 19). The DEM here is the Copernicus DEM GLO-90, served as free tiles from a public AWS bucket with “No AWS account required” (registry). Each tile is 1 by 1 degree, a Cloud Optimized GeoTIFF named by its south-west corner: Copernicus_DSM_COG_30_S09_00_E120_00_DEM covers 9-8 S, 120-121 E at 3 arc-seconds (about 90 m). Ocean has no tiles, and the provider says “there one can assume height values equal to zero” (readme). It is a surface model: forest canopy and buildings are part of the height. Section 6 shows that even setting elevation to 0 m everywhere moves ETos by only about 0.015 mm/day on average, so canopy and building heights should matter much less at 0.1 degree.
The cell below lists the tiles that touch the area, keeps those the bucket’s tileList.txt names, and downloads the missing ones into paths.downloads/dem. When tested, 27 of the 40 tiles around NTT were listed, 32 MB in all. Tiles not listed are ocean or not released.
wanted = dem.tiles_for(AOI)released = dem.released_tiles(DEM_DIR)tiles = [n for n in wanted if n in released]t0 = time.time()files = dem.download_tiles(tiles, DEM_DIR)print(f"{len(wanted)} tiles touch {AOI_NAME}; {len(tiles)} are in tileList.txt (the rest are ocean or not released); "f"{sum(f.stat().st_size for f in files) /1e6:.0f} MB; {time.time() - t0:.0f} s")
40 tiles touch ntt; 27 are in tileList.txt (the rest are ocean or not released); 32 MB; 0 s
Into GRASS. GDAL builds a virtual mosaic (a VRT: a small text file that points at the tiles) with -9999 wherever no tile exists. r.in.gdal -r imports only the part inside the current region. When tested, it kept the DEM’s own 3 arc-second cells and left the 0.1 degree region as it was. r.null then turns the no-tile cells into 0 m, as the provider advises. Negative heights that remain are real values in the surface model (a few metres below 0 on some coasts), not sea.
Units on dem90 are set last, so a re-run after an interruption repeats the whole step instead of skipping r.null.
from osgeo import gdalgdal.UseExceptions()vrt = DEM_DIR /f"cop90_{AOI_NAME}.vrt"mosaic = gdal.BuildVRT(str(vrt), [str(f) for f in files], VRTNodata=-9999)mosaic =None# closes the file and writes the VRThave_dem ="dem90"in {n.split("@")[0] for n in gs.list_strings("raster", pattern="dem90", mapset=HERE)}ifnot have_dem or Info("dem90", HERE).units !="m": Module("r.in.gdal", input=str(vrt), output="dem90", flags="r", memory=1000, overwrite=True) Module("r.null", map="dem90", null=0) Info("dem90", HERE).units ="m"info = gs.raster_info("dem90")print(f"dem90: {info['rows']} x {info['cols']} cells of {info['nsres'] *3600:.1f} arc-seconds, "f"{info['min']:.0f} to {info['max']:.0f} m")
dem90: 3841 x 7681 cells of 3.0 arc-seconds, -8 to 2392 m
Down to 0.1 degree. Two ways to give each AgERA5 cell one elevation:
r.resample takes the DEM value nearest the cell centre.
r.resamp.stats -w method=average takes the mean of every DEM cell inside, weighted by the share of it that lies inside the AgERA5 cell (the -w flag).
On a coast the centre is a poor choice. Many AgERA5 land cells are coastal, and with sea set to 0 m a centre sample gives such a cell the height of the sea next to it; with sea as no-data, as in some DEM services, it gives no value at all and the cell loses its ETos. The cell counts how many land cells have their centre at or below 0 m.
Module("r.resamp.stats", input="dem90", output="elev", method="average", flags="w", overwrite=True)Module("r.resample", input="dem90", output="elev_centre", overwrite=True)gs.run_command("r.support", map="elev", units="m", title="Copernicus GLO-90 mean per AgERA5 cell")land = np.isfinite(raster2numpy(f"tmax_{YEARS[0]}0101@{RAW}"))elev = raster2numpy("elev")centre = raster2numpy("elev_centre")print(f"AgERA5 land cells: {land.sum()}; elevation missing on land: {int((~np.isfinite(elev) & land).sum())}")print(f"Land cells whose centre sample is at or below 0 m: {int((land & (centre <=0)).sum())} "f"({(land & (centre <=0)).sum() / land.sum():.0%})")print(f"Mean elevation over land cells: {np.nanmean(elev[land]):.0f} m (max {np.nanmax(elev[land]):.0f} m)")
AgERA5 land cells: 1113; elevation missing on land: 0
Land cells whose centre sample is at or below 0 m: 689 (62%)
Mean elevation over land cells: 144 m (max 1441 m)
Look before moving on. The two elevations side by side, on land cells only (sea left blank) and on one colour scale, drawn from the arrays the cell above read. Inland the two maps should show the same highlands. On the coast they part: the centre sample gives many land cells the colour of 0 m or below, the share the cell above printed, while the mean keeps a height from the land inside the cell. A blank land cell in elev would be a problem, because ETos would be missing there in every later step.
pgca.preview draws arrays or GRASS maps on one colour scale and prints one summary line per panel (cell count, null count, minimum, mean and maximum); this chapter uses it after each step.
from pgca import preview_ = preview.array_maps([np.where(land, elev, np.nan), np.where(land, centre, np.nan)], ["elev: mean of the DEM cells inside", "elev_centre: DEM cell at the centre"], "m", extent=preview.region_extent(), cmap="terrain", ncols=2)
elev: mean of the DEM cells inside: 2,048 cells, 935 null; min 0.00, mean 143.55, max 1440.93 m
elev_centre: DEM cell at the centre: 2,048 cells, 935 null; min 0.00, mean 142.92, max 1569.85 m
The same elev map drawn by GRASS itself: gj.Map renders a raster with the GRASS display tools (d.rast, d.legend) in the current region, without the land mask used above.
m = gj.Map(width=700)m.d_rast(map="elev")m.d_legend(raster="elev", title="elevation (m)", at=(5, 40, 2, 5)) # at = bottom, top, left, right in % of the framem.show()
3. One day, step by step
The ASCE standardized equation for a daily time step (ASCE-EWRI 2005, eq 1, p4):
Symbol
Meaning
Units
standardized reference evapotranspiration: ETos for short grass, ETrs for tall alfalfa
mm d-1
slope of the saturation vapour pressure curve at the mean temperature
kPa C-1
net radiation: shortwave kept by the surface minus longwave lost
MJ m-2 d-1
soil heat flux, 0 for daily steps (eq 30)
MJ m-2 d-1
psychrometric constant, from atmospheric pressure
kPa C-1
mean air temperature, (Tmax + Tmin) / 2
C
wind speed at 2 m
m s-1
,
saturation and actual vapour pressure; is the vapour pressure deficit
kPa
,
constants for the reference crop and time step: 900 and 0.34 for short grass (Table 1)
The radiation terms need their own steps: extraterrestrial radiation (sunlight at the top of the atmosphere, from latitude and day of year), clear-sky radiation , and the ratio of the day’s solar radiation to its clear-sky value, which stands for cloudiness in the net longwave term .
The next cell writes each step as its own map for one day, 15 July 2015, following the report’s equations: unit conversions, pressure (eq 3), psychrometric constant (eq 4), the vapour pressures (eq 5-8), wind at 2 m (eq 33, which the report gives after the radiation terms), the radiation terms (eq 17-27) and the result (eq 1). The steps live in pgca.et0.mapcalc_steps() (read src/pgca/et0.py); the cell prints each as r.mapcalc receives it. Two things to know when reading them:
r.mapcalc’s trigonometric functions work in degrees: “x is in degrees” for sin(), and acos() gives its “result in degrees” (r.mapcalc). The solar declination is computed in radians, as in the report, and converted before sin(); the sunset hour angle omega_s from acos() is converted back to radians where the formula multiplies by the angle itself.
y() is the latitude of the cell centre here, in degrees, because the project is in EPSG:4326 (Chapter 2).
Wind is the 10 m AgERA5 wind times 4.87 / ln(67.8 z - 5.42) with z = 10 m (ASCE eq 33), which is 0.748.
Look before moving on. The radiation terms of the day, read back from the step maps, all in MJ m-2 d-1 on one scale. d_Ra depends only on latitude and day of year, so it should change from north to south only (bands running east-west) and cover the sea as well: its summary line should show no null cells, while the other three are blank wherever the AgERA5 inputs are. d_rs should lie below d_Ra on every land cell, since the atmosphere takes part of the sunlight; d_Rnl should be small and positive, a loss; and d_Rn is 0.77 d_rs minus d_Rnl. Any change from west to east in d_Ra, or d_rs above it, would point at an error in the radiation steps, such as degrees used where radians are meant.
_ = preview.maps(["d_Ra", "d_rs", "d_Rnl", "d_Rn"], ["Ra, top of the atmosphere", "Rs, at the ground", "Rnl, longwave lost", "Rn, net radiation"],"MJ m-2 d-1", ncols=4, suptitle=f"Radiation terms, {DAY}")
Ra, top of the atmosphere: 2,048 cells, 0 null; min 29.30, mean 29.99, max 30.67 MJ m-2 d-1
Rs, at the ground: 2,048 cells, 935 null; min 15.37, mean 19.63, max 22.85 MJ m-2 d-1
Rnl, longwave lost: 2,048 cells, 935 null; min 2.98, mean 4.27, max 5.82 MJ m-2 d-1
Rn, net radiation: 2,048 cells, 935 null; min 8.86, mean 10.84, max 12.40 MJ m-2 d-1
Look before moving on. The humidity terms in kPa, with the vapour pressure deficit es - ea computed here from the two step maps (the chapter writes no map of it), then the 2 m wind in m s-1. ea should lie below es on almost every land cell; where it does not, the deficit is negative, the case section 7 counts, and the deficit’s printed minimum shows whether this day has one. d_u2 is 0.748 times the 10 m wind, so it should show the pattern of ws10 in Chapter 3 and never a negative value.
es, saturation: 2,048 cells, 935 null; min 2.01, mean 3.18, max 3.72 kPa
ea, from the dew point: 2,048 cells, 935 null; min 1.26, mean 2.14, max 2.64 kPa
es - ea, vapour pressure deficit: 2,048 cells, 935 null; min 0.38, mean 1.03, max 1.87 kPa
u2, wind at 2 m: 2,048 cells, 935 null; min 0.71, mean 3.71, max 7.50 m s-1
One land cell’s value at every step, read from the maps with raster2numpy (which reads in the current region, so row and column follow from the region). The last line adds AgERA5’s own et0 for the same cell and day.
lat0, lon0 =-10.2, 123.6# a land cell on Timorrow, col =int((reg["n"] - lat0) / reg["nsres"]), int((lon0 - reg["w"]) / reg["ewres"])values = [float(raster2numpy(name)[row, col]) for name, _ in step_maps]table = pd.DataFrame({"step": [s[0] for s in steps], "meaning": [s[4] for s in steps],"units": [s[2] for s in steps], "source": [s[3] for s in steps], "value": values})table.loc[len(table)] = ["et0 (AgERA5)", "AgERA5's reference ET, same cell and day", "mm d-1", "Chapter 3",float(raster2numpy(f"et0_{DAY:%Y%m%d}@{RAW}")[row, col])]print(f"cell centre {LAT[row]:.2f}, {reg['w'] + reg['ewres'] * (col +0.5):.2f}")table.round(4)
cell centre -10.20, 123.60
step
meaning
units
source
value
0
tx
daily maximum air temperature
C
K to C
29.4026
1
tn
daily minimum air temperature
C
K to C
22.1471
2
td
daily mean dew point
C
K to C
15.2064
3
rs
solar radiation reaching the ground (Rs)
MJ m-2 d-1
J to MJ
20.2594
4
tm
mean temperature, from Tmax and Tmin
C
eq 2
25.7749
5
P
atmospheric pressure at the cell's elevation
kPa
eq 3
99.2904
6
gamma
psychrometric constant
kPa C-1
eq 4
0.0660
7
delta
slope of the saturation vapour pressure curve ...
kPa C-1
eq 5
0.1964
8
es
saturation vapour pressure (mean of the values...
kPa
eq 6, 7
3.3838
9
ea
actual vapour pressure, from the dew point
kPa
eq 8
1.7281
10
u2
wind speed at 2 m, from 10 m
m s-1
eq 33
3.7281
11
dr
inverse relative Earth-Sun distance
-
eq 23
0.9679
12
dec
solar declination
rad
eq 24
0.3746
13
omega_s
sunset hour angle
rad
eq 27
1.5000
14
Ra
extraterrestrial radiation (top of the atmosph...
MJ m-2 d-1
eq 21
29.7024
15
Rso
clear-sky solar radiation
MJ m-2 d-1
eq 19
22.3786
16
ratio
relative solar radiation Rs/Rso, limited
-
eq 18 limits
0.9053
17
Rnl
net longwave radiation lost by the surface
MJ m-2 d-1
eq 17, 18
5.3281
18
Rn
net radiation: shortwave kept (albedo 0.23) mi...
MJ m-2 d-1
Rns - Rnl
10.2716
19
et
reference evapotranspiration; soil heat flux G...
mm d-1
eq 1, G = 0 (eq 30)
5.9249
20
et0 (AgERA5)
AgERA5's reference ET, same cell and day
mm d-1
Chapter 3
5.8814
Look before moving on. The result d_et next to AgERA5’s own et0 for the same day, in mm d-1 on one scale. The table compared one cell; the maps compare all of them. They should be hard to tell apart: the same blank sea cells, the same pattern, and close means on the two summary lines. A difference in pattern (bands from north to south, say) would point at a radiation term; a difference of about the same amount everywhere, at a unit conversion or a constant. Section 4 checks the formula itself.
_ = preview.maps(["d_et", f"et0_{DAY:%Y%m%d}@{RAW}"], ["ETos, this chapter (d_et)", "et0, AgERA5"], "mm d-1", cmap="YlGnBu", ncols=2, suptitle=f"Reference ET, {DAY}")
ETos, this chapter (d_et): 2,048 cells, 935 null; min 2.94, mean 4.67, max 6.36 mm d-1
et0, AgERA5: 2,048 cells, 935 null; min 2.94, mean 4.64, max 6.26 mm d-1
4. Checking the formula
Against a published example. FAO-56 Example 18 computes daily ET0 for Uccle (Brussels) on 6 July and prints every intermediate value (FAO-56 chapter 4). Its humidity and radiation come from relative humidity and sunshine hours, so the cell takes three of the example’s intermediate values as given: actual vapour pressure (1.409 kPa), wind at 2 m (2.078 m s-1) and solar radiation (22.07 MJ m-2 d-1). It runs them through pgca.et0.etsz(), the numpy version of the same steps. The example prints values rounded to its own decimals; the table compares at those decimals. FAO-56 uses the Stefan-Boltzmann constant 4.903e-9 and this code 4.901e-9; at the printed decimals that makes no difference. The example’s result is the sum of a radiation term (2.81 mm/day) and an aerodynamic term (1.07 mm/day). The test suite (tests/test_et0.py) runs the same check.
ex18 =dict(tmax_c=21.5, tmin_c=12.3, ea=1.409, u2=2.078, rs=22.07, z=100.0, lat_deg=50+48/60, doy=187)printed = {"P": 100.1, "gamma": 0.0666, "delta": 0.122, "es": 1.997, "Ra": 41.09, "Rso": 30.90,"Rns": 17.00, "Rnl": 3.71, "Rn": 13.28}result, parts = et0.etsz(**ex18, parts=True)check = pd.DataFrame({"FAO-56 printed": printed, "pgca.et0": {k: float(parts[k]) for k in printed}})check["equal at printed decimals"] = [round(check.at[k, "pgca.et0"], len(str(v).split(".")[1])) == v for k, v in printed.items()]print(f"ET0: pgca.et0 {float(result):.3f} mm/day; FAO-56 prints 2.81 + 1.07 = 3.9 mm/day")check
GRASS against numpy. The same formula in numpy, on the same input maps read into arrays, must give the map d_et of section 3. The arrays are converted to double precision first, as r.mapcalc does with its inputs, so the two should agree to rounding.
arr = {v: raster2numpy(name).astype(float) for v, name inzip(INPUTS, inputs_for(DAY))}et_np = et0.etsz_agera5(arr["tmax"], arr["tmin"], arr["tdew"], arr["ws10"], arr["srad"], elev.astype(float), LAT[:, None], DAY.timetuple().tm_yday)grass_et = raster2numpy("d_et")print(f"max |GRASS - numpy| = {np.nanmax(np.abs(grass_et - et_np)):.1e} mm/day; "f"null cells identical: {np.array_equal(np.isnan(grass_et), np.isnan(et_np))}")print(f"Mean ETos over land on {DAY}: {np.nanmean(grass_et):.2f} mm/day")
max |GRASS - numpy| = 9.5e-11 mm/day; null cells identical: True
Mean ETos over land on 2015-07-15: 4.67 mm/day
5. Every day of the record
pgca.et0.mapcalc_expression() joins the steps into one r.mapcalc expression with eval(), which computes the named intermediate values without writing them as maps (“the temporary variables (maps) are not created”, r.mapcalc). It wraps the result in float(), so each map is stored in single precision like the inputs, half the disk of the double precision r.mapcalc would otherwise write.
What remains is running it for every day. Three routes were timed on the 365 days of 2015, 8 processes at a time, on Windows 11 with 80 logical CPUs:
Route
Time for 365 days
t.rast.mapcalc over the five datasets (registers the result too)
147.5 s
One r.mapcalc per day
79.5 s
One r.mapcalc per 10 days, one expression per line of a file
14.0 s
Two findings behind the table:
Most of a short GRASS call is starting it. One r.mapcalc call on this small area took 0.24 s, about as long as g.region (0.22 s). Ten days per call pays the start once for ten maps. With 30 days (or all 365) per call, r.mapcalc failed with “Too many open files” when tested; 10 worked. The likely reason is that r.mapcalc holds every map named in the file open at once, five inputs and one output per day; the manual does not say.
Threads cost more than they give on a small area. r.mapcalc’s nprocs option defaults to 0, “use OpenMP default”, which on the test machine meant all 80 logical CPUs. One call took 1.1 s that way and 0.24 s with nprocs=1. That is why the setup cell set NPROCS=1, and why run_et() below also passes nprocs=1. (t.rast.mapcalc already starts each r.mapcalc with one thread; its own nprocs sets how many r.mapcalc processes run at once.)
run_et() writes one file of 10 lines per 10 days into paths.outputs/ch04/mapcalc (you can open one to see the full expression) and runs those files up to 8 at a time. label() sets semantic label and units, units last.
CHUNK =10def run_et(prefix, crop, days): queue = ParallelModuleQueue(nprocs=N_PARALLEL)for k inrange(0, len(days), CHUNK): lines = [f"{prefix}_{d:%Y%m%d} = "+ et0.mapcalc_expression(*inputs_for(d), f"elev@{HERE}", d.timetuple().tm_yday, crop)for d in days[k:k + CHUNK]] path = OUT_DIR /"mapcalc"/f"{prefix}_{days[k]:%Y%m%d}.txt" path.write_text("\n".join(lines) +"\n") queue.put(Module("r.mapcalc", file=str(path), nprocs=1, overwrite=True, run_=False)) queue.wait()def label(prefix, days, semantic):for d in days: info = Info(f"{prefix}_{d:%Y%m%d}", HERE) info.semantic_label = semantic info.units ="mm d-1"# last: units mark the map as finished
Slow cell on the full record: when tested, 1,016 s for the 17,167 days (59 ms per day; 461 s in an earlier run on the same machine). It skips days already done and recomputes any day whose map has no units yet, so it can be interrupted and re-run. The last line checks the one-expression route against the step maps of section 3.
finished = done("etos")todo = [d for d in DAYS iff"etos_{d:%Y%m%d}"notin finished]t0 = time.time()run_et("etos", "short", todo)t_compute = time.time() - t0label("etos", todo, "etos")print(f"computed {len(todo):,} days in {t_compute:.0f} s ({t_compute /max(len(todo), 1) *1000:.0f} ms per day), "f"labels {time.time() - t0 - t_compute:.0f} s; {len(DAYS) -len(todo):,} were already done")diff_route = np.nanmax(np.abs(raster2numpy(f"etos_{DAY:%Y%m%d}") - grass_et))print(f"one expression vs step maps on {DAY}: max difference {diff_route:.1e} mm/day (single precision rounding)")
computed 17,167 days in 1016 s (59 ms per day), labels 40 s; 0 were already done
one expression vs step maps on 2015-07-15: max difference 2.4e-07 mm/day (single precision rounding)
Look before moving on. Four of the daily maps the cell above wrote (or found finished), the 15th of January, April, July and October of the section 3 year, in mm d-1 on one scale. Each should be filled on land and blank at sea, like d_et, with values inside the range the checkpoint tests (-0.5 to 15 mm per day). The 15 July map is the one-expression version of d_et; the cell above printed their largest difference. A map blank everywhere, or an error that a map is missing, would mean one of the r.mapcalc files failed; re-running the cell above computes only the days without units.
show_days = [dt.date(DAY.year, m_, 15) for m_ in (1, 4, 7, 10)]_ = preview.maps([f"etos_{d:%Y%m%d}"for d in show_days], [f"{d:%d %b %Y}"for d in show_days], "mm d-1", cmap="YlGnBu", ncols=4, suptitle="ETos on four days")
15 Jan 2015: 2,048 cells, 935 null; min 2.84, mean 4.46, max 5.89 mm d-1
15 Apr 2015: 2,048 cells, 935 null; min 3.58, mean 4.71, max 5.74 mm d-1
15 Jul 2015: 2,048 cells, 935 null; min 2.94, mean 4.67, max 6.36 mm d-1
15 Oct 2015: 2,048 cells, 935 null; min 4.47, mean 5.50, max 6.81 mm d-1
Register the maps in a dataset etos with pgca.tgis.register_daily(), the Chapter 3 pattern moved into a helper: create the dataset only if missing, register only maps it does not hold yet, and rebuild the summary if an interrupted registration left it stale.
The dataset’s semantic typesum describes the whole dataset (each value is a total over the day). It is metadata only: Chapter 5 must still ask t.rast.aggregate for method=sum. The semantic labeletos set above belongs to each map and says what the map is.
Slow cell on the full record: when tested, 260 s for 17,167 maps (15 ms per map).
t0 = time.time()n_new = tgis.register_daily("etos", HERE, [(f"etos_{d:%Y%m%d}", d) for d in DAYS], OUT_DIR /"register_etos.txt","ASCE standardized short reference ET",f"ASCE-EWRI 2005 ETos from AgERA5, {AOI_NAME}, daily, pgca.et0")t_register = time.time() - t0info = tgis.info("etos")print(f"registered {n_new:,} new maps in {t_register:.0f} s; etos holds {info['number_of_maps']} maps, "f"{info['start_time']} to {info['end_time']}, min {float(info['min_min']):.2f}, max {float(info['max_max']):.2f} mm/day")
registered 17,167 new maps in 260 s; etos holds 17167 maps, 1979-01-01 00:00:00 to 2026-01-01 00:00:00, min -0.12, max 8.42 mm/day
Look before moving on. What the dataset itself records for one year, the section 3 year: t.rast.list returns, for each registered map, its start time and the lowest and highest cell value stored in the temporal database. The plot reads no maps, so it checks the registration rather than the rasters. Each line should have one value per day (365 for 2015; the summary lines count them), and both should stay inside the range the checkpoint tests (-0.5 to 15 mm per day). A smaller count means days not registered. The lines change from day to day with the weather; the space between them is the spread over the area on that day.
listed = json.loads(gs.read_command("t.rast.list", input="etos", columns="start_time,min,max", format="json", where=f"start_time >= '{DAY.year}-01-01' and start_time < '{DAY.year +1}-01-01'"))["data"]_ = preview.series(pd.to_datetime([r_["start_time"] for r_ in listed]), {"lowest cell": [float(r_["min"]) for r_ in listed], "highest cell": [float(r_["max"]) for r_ in listed]},"mm d-1", title=f"etos in {DAY.year}: lowest and highest cell of each day, from t.rast.list")
lowest cell: 365 values, 0 null; min 0.80, mean 3.19, max 4.60 mm d-1
highest cell: 365 values, 0 null; min 4.27, mean 5.97, max 7.69 mm d-1
6. Comparing with AgERA5
The comparison reads both datasets into numpy one year at a time, because the statistics wanted are simplest there. Reading the 34,334 maps of the full record took 727 s when tested (158 s in an earlier run).
For each year the table gives, over all land cell-days, with diff = ETos - et0 in mm/day (positive where this chapter’s value is higher):
et0 mean and etos mean: the two products’ averages;
bias: the mean of diff;
rmse: the root-mean-square of diff, the typical size of a daily difference;
p99 |diff| and max |diff|: the 99th percentile and the largest absolute difference.
On a full run the table has 47 rows, so the cell shows their summary (count, mean, spread, minimum, maximum of each column) instead; all rows are in etos_vs_et0_by_year.csv.
def stack(prefix, mapset, days):return np.stack([raster2numpy(f"{prefix}_{d:%Y%m%d}@{mapset}") for d in days])rows, worst, sample = [], [], []sum_diff, n_days = np.zeros(land.shape), 0rng = np.random.default_rng(4) # fixed seed: the same random sample every runcells_rc = np.argwhere(land)t0 = time.time()for y in YEARS: days = days_of(y) a, b = stack("etos", HERE, days), stack("et0", RAW, days) d = (a - b)[:, land] rows.append({"year": y, "et0 mean": np.nanmean(b[:, land]), "etos mean": np.nanmean(a[:, land]),"bias": np.nanmean(d), "rmse": np.sqrt(np.nanmean(d **2)),"p99 |diff|": np.nanpercentile(np.abs(d), 99), "max |diff|": np.nanmax(np.abs(d))}) sum_diff += np.nansum(a - b, axis=0) n_days +=len(days) pick = rng.choice(d.size, 2000, replace=False) sample.append(np.column_stack([b[:, land].ravel()[pick], a[:, land].ravel()[pick]]))for i in np.argsort(np.abs(d), axis=None)[-5:]: # five largest differences of the year t, c = np.unravel_index(i, d.shape) r_, c_ = cells_rc[c] worst.append({"date": days[t], "lat": round(LAT[r_], 2), "lon": round(reg["w"] + reg["ewres"] * (c_ +0.5), 2),"diff": d[t, c], "et0": b[t, r_, c_], "elev m": elev[r_, c_]})per_year = pd.DataFrame(rows).set_index("year")per_year.to_csv(OUT_DIR /"etos_vs_et0_by_year.csv")print(f"read {2* n_days:,} maps in {time.time() - t0:.0f} s; mean daily et0 over land {per_year['et0 mean'].mean():.2f} mm/day")per_year.round(4) iflen(per_year) <=10else per_year.describe().round(4)
read 34,334 maps in 727 s; mean daily et0 over land 4.49 mm/day
et0 mean
etos mean
bias
rmse
p99 |diff|
max |diff|
count
47.0000
47.0000
47.0000
47.0000
47.0000
47.0000
mean
4.4934
4.4937
0.0003
0.0419
0.1513
0.5376
std
0.0854
0.0862
0.0017
0.0017
0.0102
0.0916
min
4.3091
4.3070
-0.0051
0.0375
0.1264
0.3795
25%
4.4264
4.4256
-0.0008
0.0406
0.1438
0.4743
50%
4.5048
4.5045
0.0004
0.0419
0.1507
0.5286
75%
4.5586
4.5588
0.0016
0.0432
0.1570
0.5827
max
4.6705
4.6736
0.0032
0.0453
0.1753
0.7775
Where the differences are: a map of the mean difference per cell (written to GRASS as etos_minus_et0_mean), and a random sample of 2,000 land cell-days per year plotted against each other. The colour scale of the map is fixed at plus and minus 0.1 mm/day, so teaching and full runs can be compared by eye.
Look before moving on. In the left panel the cell-days should lie along the white 1:1 line over the whole range: a curve away from it at high values, or a band parallel to it, would be a systematic difference to trace before going on. In the right panel, compare the pattern with the elevation map of section 2; bands running east-west would instead point at a latitude-dependent term, the radiation. The paragraph after the next table reads both panels.
Over 1979-2025, when tested, the yearly bias stayed between -0.005 and +0.003 mm/day and the yearly root-mean-square difference between 0.038 and 0.045 mm/day, against a mean et0 of 4.49 mm/day: about 1%. Single cell-days differ by up to 0.78 mm/day.
Two patterns show:
The mean difference follows elevation. Its correlation with the Copernicus elevation over land cells is +0.69: +0.034 mm/day on average in cells above 500 m, -0.004 in cells at 0 m. A higher elevation raises ETos (the elevation 0 m test below lowers it), so AgERA5’s et0 behaves as if its elevation were lower than the Copernicus mean in the highlands. That would fit a smoother elevation model. The AgERA5 user guide says its data are represented by the elevation of the ECMWF HRES model at 0.1 degree (PUGS, section 3.5), but not which elevation its et0 calculation uses, so this stays a likely explanation, not a confirmed one.
The largest single differences are on the coast. All ten in the table are in cells with no land in the DEM (elevation 0 m), around 10.4-10.5 S, 120.0-120.6 E and 11.1 S, 123.1-123.3 E, on single days and with both signs. Their cause was not traced.
Testing what the documents leave open. AgERA5’s algorithm description does not state how its 10 m wind becomes 2 m wind, which elevation it uses, or whether PCSE’s details were kept. Each can be tested: recompute with the alternative and see whether it comes closer to et0. The variants:
the PCSE helper wind10to2, a logarithmic profile with a surface roughness of 0.033 m: factor log(2/0.033)/log(10/0.033) = 0.718 instead of 0.748;
elevation 0 m everywhere;
FAO-56’s limits instead of ASCE’s;
a numpy copy of PCSE’s whole penman_monteith, pgca.et0.pcse_et0(): its own extraterrestrial radiation (astro()), 70/208 = 0.337 in place of Cd 0.34, no Rs/Rso limits, vapour pressure capped at saturation, and the PCSE wind factor.
The variants run in numpy on the prepared files of Chapter 3 (paths.staged), which hold the same values as the GRASS input maps, for the teaching years only. That needs no new maps (each GRASS variant would mean another 731 maps written, labelled and read back), and the GRASS route equals numpy (section 4). The first row repeats this chapter’s calculation for 2015-2016, so it should match the 2015 and 2016 rows of the yearly comparison (etos_vs_et0_by_year.csv); it is a free check.
The prepared files and the arrays made here (arrs, doy, variant()) are used again in section 7.
def staged(var, years): out = []for y in years:with xr.open_dataset(STAGED / var /f"{var}_{y}_{AOI_NAME}.nc") as ds: out.append(ds[NC[var]].values.astype(float))return np.concatenate(out)arrs = {v: staged(v, TEACH) for v in INPUTS + ["et0"]}doy = np.array([d.timetuple().tm_yday for y in TEACH for d in days_of(y)])[:, None, None]LAT3 = LAT[None, :, None]PCSE_WIND = np.log10(2/0.033) / np.log10(10/0.033)def variant(**kw): kw =dict(kw) z = kw.pop("z", elev)return et0.etsz_agera5(arrs["tmax"], arrs["tmin"], arrs["tdew"], arrs["ws10"], arrs["srad"], z, LAT3, doy, **kw)def pcse_copy(): tx, tn = arrs["tmax"] -273.15, arrs["tmin"] -273.15return et0.pcse_et0(tx, tn, et0.e0(arrs["tdew"] -273.15), arrs["ws10"] * PCSE_WIND, arrs["srad"], elev, LAT3, doy)
The next cell computes the five variants over the teaching years and compares each with et0 on the land cell-days, with the bias, root-mean-square and 99th percentile columns of the yearly table.
t0 = time.time()variants = {"ASCE 2005 (this chapter)": variant(),"wind factor 0.718 (PCSE wind10to2)": variant(wind=PCSE_WIND),"elevation 0 m": variant(z=0.0),"FAO-56 limits (sigma 4.903e-9, Rs/Rso <= 1, u2 >= 0.5)": variant(sigma=4.903e-9, ratio_limits=(-np.inf, 1.0), u2_min=0.5),"PCSE copy (its Ra, 70/208, no limits, ea <= es, wind 0.718)": pcse_copy(),}rows = []for name, e in variants.items(): d = (e - arrs["et0"])[:, land] rows.append({"variant": name, "bias": np.nanmean(d), "rmse": np.sqrt(np.nanmean(d **2)),"p99 |diff|": np.nanpercentile(np.abs(d), 99)})sens = pd.DataFrame(rows).set_index("variant")sens.to_csv(OUT_DIR /"sensitivity_teaching_years.csv")print(f"{len(variants)} variants in {time.time() - t0:.0f} s; columns as in the yearly table (mm/day, variant - et0)")sens.round(4)
5 variants in 2 s; columns as in the yearly table (mm/day, variant - et0)
bias
rmse
p99 |diff|
variant
ASCE 2005 (this chapter)
0.0004
0.0418
0.1513
wind factor 0.718 (PCSE wind10to2)
-0.0149
0.0428
0.1570
elevation 0 m
-0.0150
0.0460
0.1527
FAO-56 limits (sigma 4.903e-9, Rs/Rso <= 1, u2 >= 0.5)
0.0003
0.0416
0.1499
PCSE copy (its Ra, 70/208, no limits, ea <= es, wind 0.718)
-0.0029
0.0396
0.1477
When tested over the teaching years, the closest variant was the PCSE copy (root-mean-square difference 0.040 mm/day), then the FAO-56 limits and this chapter’s ASCE calculation (0.042 for both, with biases of 0.0003 and 0.0004 mm/day). The first row agrees with the 2015 and 2016 rows of the yearly comparison (0.0425 and 0.0411), as it should. Changing only the wind factor to PCSE’s 0.718, or only the elevation to 0 m, moves the bias to about -0.015 mm/day; in the full PCSE copy its other details move the bias back by about 0.012 mm/day, to -0.003. So AgERA5’s et0 behaves much like the PCSE code it says it derives from, which is consistent with, not proof of, AgERA5 using it unchanged.
No variant removes the daily differences: about 0.04 mm/day remain in every one, with single cell-days near 0.5 mm/day. One candidate was not tested. AgERA5 computes its own daily vapour pressure from the dew point (ATBD); if that is a mean of hourly values rather than the vapour pressure of the daily mean dew point used here, the two differ. The archive used for this series has no vapour pressure variable to check it.
7. Odd inputs
Chapter 3 found days in the source data that should not occur physically. Each meets the formula in a different place:
Dew point high. When ea, from the dew point, exceeds es, the mean of the saturation values at Tmax and Tmin, the vapour pressure deficit (es - ea) turns negative. A dew point above Tmax always does this; one a little below Tmax can too. Neither ASCE 2005 nor FAO-56 says what to do. PCSE caps ea at es.
Wind near zero. ASCE states no lower limit. FAO-56 recommends u2 >= 0.5 m s-1, because in calm air rising warm air still moves vapour away from the surface (FAO-56 chapter 3, section “Missing wind speed data”).
Very low solar radiation (one cell-day of exactly zero in 1979-2025, 21 June 2013, Chapter 3). The cloudiness factor in Rnl is 1.35 Rs/Rso - 0.35, which turns negative below Rs/Rso = 0.26 and makes the longwave term a gain. ASCE limits Rs/Rso to at least 0.3, which keeps the factor at 0.05 or more (p20); FAO-56 sets no lower limit.
Tmin above Tmax does not upset the formula: the two enter only through means (of the temperatures, of their saturation vapour pressures, and of their fourth powers), none of which needs the order. There is no alternative to test.
This chapter uses ASCE 2005 as written, since it is the standard EDDI cites, and reports what each alternative would change. The cell counts each case over the teaching years (with arrs, doy and variant() from section 6) and measures the change, alternative minus ASCE as written, on the affected cell-days only.
Teaching years: negative ETos cell-days with ASCE as written: 0; minimum 0.37 mm/day
Whole run (1979-2025): 2 etos maps have a negative minimum
etos_20000511: 1 cell(s), -0.034 mm/day at -9.80, 124.60; Tdew - Tmax -0.17 K, Rs 0.19 MJ m-2, AgERA5 et0 0.42 mm/day
etos_20130621: 1 cell(s), -0.117 mm/day at -9.80, 124.60; Tdew - Tmax +0.26 K, Rs 0.00 MJ m-2, AgERA5 et0 0.38 mm/day
cell-days
share %
alternative
mean change (mm/day)
largest change (mm/day)
case
ea > es (dew point high)
7
0.0009
cap ea at es
0.0639
0.1507
u2 < 0.5 m/s
3301
0.4057
FAO-56 floor u2 >= 0.5
0.0089
0.1510
Rs/Rso < 0.3
1724
0.2119
no lower limit (FAO-56)
0.0741
0.3232
Tmin > Tmax
168
0.0206
none to test
NaN
NaN
Look before moving on. Where the odd inputs occur: for each case of the table, the number of teaching-year days on which it happens in each land cell, from the masks the cell above built (cases). The cases differ widely in frequency (the cell-days column of the table), so each panel has its own colour scale; the summary lines give the count per land cell. Look at whether a case is spread over the area or gathered in a few cells. One gathered in a handful of cells, on the coast for example, says more about the input data of those cells than about the weather, and is worth a look at those cells in Chapter 3’s maps.
fig, axes = plt.subplots(1, len(cases), figsize=(3.4*len(cases), 2.6), constrained_layout=True)extent_ = preview.region_extent()per_cell = {case_: np.where(land, spec_[0].sum(axis=0), np.nan) for case_, spec_ in cases.items()}for ax, (case_, count_) inzip(axes, per_cell.items()): im = ax.imshow(count_, extent=extent_, cmap="magma_r", interpolation="nearest") ax.set_title(case_, fontsize=9) ax.tick_params(labelsize=7) fig.colorbar(im, ax=ax, shrink=0.8).set_label("days", fontsize=8)plt.show()for case_, count_ in per_cell.items():print(preview.format_summary(case_, preview.summary(count_[land]), "days per land cell"))
ea > es (dew point high): 1,113 cells, 0 null; min 0.00, mean 0.01, max 3.00 days per land cell
u2 < 0.5 m/s: 1,113 cells, 0 null; min 0.00, mean 2.97, max 157.00 days per land cell
Rs/Rso < 0.3: 1,113 cells, 0 null; min 0.00, mean 1.55, max 9.00 days per land cell
Tmin > Tmax: 1,113 cells, 0 null; min 0.00, mean 0.15, max 5.00 days per land cell
When tested over the teaching years:
ea > es on 7 land cell-days. Capping ea at es would raise ETos there by 0.06 mm/day on average, at most 0.15.
u2 below 0.5 m/s on 3,301 cell-days (0.41%). The FAO-56 floor would raise ETos by 0.009 mm/day on average, at most 0.15.
Rs/Rso below 0.3, the cloudiest days, on 1,724 cell-days (0.21%). Without ASCE’s lower limit the longwave loss shrinks further and ETos would rise by 0.07 mm/day on average, at most 0.32.
Tmin above Tmax on 168 cell-days; nothing to test.
No cell-day of the teaching years gave a negative ETos (the minimum was 0.37 mm/day). Over 1979-2025, when tested, two cell-days did, both in the cell at 9.8 S, 124.6 E: -0.03 mm/day on 11 May 2000 and -0.12 mm/day on 21 June 2013, the day of zero solar radiation found in Chapter 3. On both the dew point was above Tmin and within 0.3 K of Tmax, so ea exceeded es, and the sun was almost absent (0.19 and 0 MJ m-2), so the vapour pressure deficit and the net radiation were both negative; AgERA5’s et0 there was 0.42 and 0.38 mm/day. The series keeps these values, as ASCE as written gives them, rather than setting them to zero as PCSE does; over a window of weeks they change a sum by a fraction of a millimetre. Each alternative touches well under 1% of cell-days, by at most a few tenths of a millimetre, so the series keeps ASCE as written and says so.
8. The tall reference, the one EDDI uses
ASCE 2005 standardizes two reference surfaces: short grass about 0.12 m tall (ETos, Cn 900 and Cd 0.34) and full-cover alfalfa about 0.50 m tall (ETrs, Cn 1600 and Cd 0.38) (ASCE-EWRI 2005, Tables 1 and 2). Cn and Cd carry the crop’s height and its resistance to evaporation into the equation. EDDI is built on the tall one: NOAA’s operational EDDI uses a “0.5-m tall reference crop” (NOAA PSL EDDI), as the paper that introduced the index also states (Hobbins et al. 2016, p. 1747). AgERA5’s et0 follows FAO-56, whose reference is “the hypothetical grass reference surface” (FAO-56 chapter 4).
That is why this chapter computes both. Sections 3 to 7 checked the code with the short crop, the only one AgERA5 can check. The tall reference is the same code with crop="tall", so that check carries over to it; the cell computes it for every day of the record as dataset etrs, the input of Chapter 5.
Slow cell on the full record: when tested, 362 s to compute the 17,167 days, 40 s for the labels and 245 s to register them. It skips days already done, like section 5.
finished = done("etrs")todo = [d for d in DAYS iff"etrs_{d:%Y%m%d}"notin finished]t0 = time.time()run_et("etrs", "tall", todo)t_compute = time.time() - t0label("etrs", todo, "etrs")t_label = time.time() - t0 - t_computen_new = tgis.register_daily("etrs", HERE, [(f"etrs_{d:%Y%m%d}", d) for d in DAYS], OUT_DIR /"register_etrs.txt","ASCE standardized tall reference ET",f"ASCE-EWRI 2005 ETrs from AgERA5, {AOI_NAME}, daily, pgca.et0")print(f"computed {len(todo):,} days in {t_compute:.0f} s, labels {t_label:.0f} s, "f"registered {n_new:,} new maps in {time.time() - t0 - t_compute - t_label:.0f} s; "f"{len(DAYS) -len(todo):,} were already done")info_rs = tgis.info("etrs")print(f"etrs holds {info_rs['number_of_maps']} maps, {info_rs['start_time']} to {info_rs['end_time']}, "f"min {float(info_rs['min_min']):.2f}, max {float(info_rs['max_max']):.2f} mm/day")
computed 17,167 days in 362 s, labels 40 s, registered 17,167 new maps in 245 s; 0 were already done
etrs holds 17167 maps, 1979-01-01 00:00:00 to 2026-01-01 00:00:00, min -0.16, max 12.12 mm/day
The minimum over the record is slightly below 0, as for ETos (section 7). Both datasets are read back for the teaching years, on land cells only, to compare their means.
TEACH_DAYS = [d for y in TEACH for d in days_of(y)]tall, short = stack("etrs", HERE, TEACH_DAYS)[:, land], stack("etos", HERE, TEACH_DAYS)[:, land]print(f"teaching years over land: mean ETrs {np.nanmean(tall):.2f}, mean ETos {np.nanmean(short):.2f} mm/day, "f"ratio of the means {np.nanmean(tall) / np.nanmean(short):.3f}")
teaching years over land: mean ETrs 5.32, mean ETos 4.56 mm/day, ratio of the means 1.166
Look before moving on. The two references for one day (15 July 2015, the section 3 day), in mm d-1 on one scale, then their ratio cell by cell. ETrs differs from ETos only through Cn and Cd, so both maps should have the same blank sea cells and a similar pattern, ETrs the higher. The ratio map shows how far apart the two references are on each cell; a ratio of exactly 1 everywhere would mean the crop setting never reached r.mapcalc. The ratio’s printed mean is for one day and the ratio of the means above for the teaching years, so the two need not agree.
ETos, short grass: 2,048 cells, 935 null; min 2.94, mean 4.67, max 6.36 mm d-1
ETrs, tall alfalfa: 2,048 cells, 935 null; min 3.16, mean 6.18, max 9.38 mm d-1
ETrs / ETos, 2015-07-15: 2,048 cells, 935 null; min 1.074, mean 1.311, max 1.489 ratio
9. Checkpoint
Chapter 5 needs etrs with one map per day of the record, finished (units set), with values exactly where the inputs have them and within a physical range; etos must pass the same tests and agree with AgERA5 within a stated limit, since that agreement is what vouches for the code both share. The agreement limit is a root-mean-square difference below 0.1 mm per day in every year: more than twice the largest yearly value seen when tested, and far below what a wrong formula causes (the extraterrestrial radiation error listed under Troubleshooting moved the bias by about 1.2 mm per day in a numpy test). The range check asks for nothing below -0.5 or above 15 mm per day, for both references. ASCE as written allows small negative values on days with a very high dew point and almost no sun (section 7); 15 is above the largest value seen (12.12 mm per day, for ETrs).
The cell re-reads what it checks from GRASS and from paths.outputs, so it also works after a kernel restart with only Setup and the helpers run.
t0 = time.time()assert gs.gisenv()["MAPSET"] == HEREland = np.isfinite(raster2numpy(f"tmax_{YEARS[0]}0101@{RAW}"))assertint((~np.isfinite(raster2numpy("elev")) & land).sum()) ==0, "elevation missing on a land cell"for ref in ("etos", "etrs"):assert {f"{ref}_{d:%Y%m%d}"for d in DAYS} <= tgis.registered(ref), f"{ref}: days missing"assert {f"{ref}_{d:%Y%m%d}"for d in DAYS} <= done(ref), f"{ref}: maps without units"for d in (DAYS[0], DAYS[len(DAYS) //2], DAYS[-1]):assert np.array_equal(np.isfinite(raster2numpy(f"{ref}_{d:%Y%m%d}")), land), f"{ref}{d}: nulls differ from land" info = tgis.info(ref)assert-0.5<float(info["min_min"]) andfloat(info["max_max"]) <15, f"{ref} outside -0.5 to 15 mm/day"info, info_rs = tgis.info("etos"), tgis.info("etrs")by_year = pd.read_csv(OUT_DIR /"etos_vs_et0_by_year.csv", index_col="year")assertset(YEARS) <=set(by_year.index) and (by_year.loc[YEARS, "rmse"] <0.1).all(), "etos and et0 disagree"n_files, mb = tgis.folder_stats(PROJECT / HERE)print(f"etos: {info['number_of_maps']} maps, {info['start_time']} to {info['end_time']}, "f"{float(info['min_min']):.2f} to {float(info['max_max']):.2f} mm/day; "f"largest yearly RMSE vs et0 {by_year.loc[YEARS, 'rmse'].max():.3f} mm/day (limit 0.1)")print(f"etrs: {info_rs['number_of_maps']} maps, {info_rs['start_time']} to {info_rs['end_time']}, "f"{float(info_rs['min_min']):.2f} to {float(info_rs['max_max']):.2f} mm/day")print("All checks passed."+ (""if RUN_FULL else" This was the teaching run: Chapter 5 needs run_full: true."))print(f"Mapset {HERE}: {n_files:,} files, {mb:.0f} MB | DEM folder: {tgis.folder_stats(DEM_DIR)[1]:.0f} MB")print(f"Checkpoint {time.time() - t0:.0f} s | chapter run time: {time.time() - CHAPTER_START:.0f} s")
etos: 17167 maps, 1979-01-01 00:00:00 to 2026-01-01 00:00:00, -0.12 to 8.42 mm/day; largest yearly RMSE vs et0 0.045 mm/day (limit 0.1)
etrs: 17167 maps, 1979-01-01 00:00:00 to 2026-01-01 00:00:00, -0.16 to 12.12 mm/day
All checks passed.
Mapset ch04: 446,627 files, 317 MB | DEM folder: 33 MB
Checkpoint 130 s | chapter run time: 2898 s
Summary
What now exists:
Mapset ch04: dem90 (Copernicus GLO-90 over the area, sea as 0 m), elev (its mean per AgERA5 cell, m) and elev_centre (the centre sample, for comparison); the step maps d_* of 15 July 2015; daily etos_YYYYMMDD (mm/day) in dataset etos and etrs_YYYYMMDD in dataset etrs; and etos_minus_et0_mean.
On disk: the DEM tiles and cop90_<area>.vrt in paths.downloads/dem; in paths.outputs/ch04, the r.mapcalc files (mapcalc/), etos_vs_et0_by_year.csv, sensitivity_teaching_years.csv and the registration files.
In src/pgca: et0.py (the ASCE steps in numpy and as r.mapcalc text, and a numpy copy of PCSE’s method), dem.py (Copernicus tiles) and tgis.py (registration helpers), with tests in tests/test_et0.py.
What you can now do: bring any DEM to a coarse grid without losing coastal cells, turn a published equation into checked GRASS maps, run it over decades of days in minutes, and test which settings explain a difference between two products.
Before Chapter 5, if you ran the teaching years: set run_full: true, restart the kernel and run the chapter again. Finished days are skipped.
Chapter 5 sums etrs over windows of weeks to months and ranks each window against the same window in other years: the Evaporative Demand Drought Index.
Troubleshooting
Symptom
Cause
Fix
AssertionError: tmax: run Chapter 3 ...
Chapter 3 imported fewer years than this run needs
run Chapter 3 with the same run_full setting
FileNotFoundError for a file in paths.staged (section 6)
Chapter 3’s prepared files are missing
re-run Chapter 3 section 4, or point paths.staged at them
HTTPError or URLError in section 2
no internet, or the bucket is unreachable
re-run section 2; finished tiles are skipped
Too many open files from r.mapcalc
30 or more days per file (10 worked when tested)
keep CHUNK = 10
Section 5 is much slower than the timings above
tools run with all threads
keep g.gisenv set=NPROCS=1 in the setup cell, and nprocs=1 in run_et()
ETos about 1.2 mm/day too high on average, mean Rnl negative
Ra computed as 24 x 60 x pi / Gsc instead of (24 x 60 / pi) x Gsc with Gsc = 0.0820 MJ m-2 min-1 (FAO-56); pgca.et0 writes the same as (24 / pi) x 4.92 with Gsc in MJ m-2 h-1 (ASCE). Found in one GEE script while preparing this chapter
compare your Ra with FAO-56 Example 18 (41.09 MJ m-2 d-1)
ETos empty on many coastal cells
elevation sampled at cell centres with sea as no-data
r.null null=0 on the DEM, then r.resamp.stats -w method=average (section 2)
t.list ... syntax of the command is incorrect
separator="|" on Windows
use separator="pipe"
GrassError ... not found in current mapset from Info
setting units on a map outside ch04
start the kernel in ch04 (setup cell)
You interrupted section 5
some maps are written but have no units
re-run section 5; maps without units are recomputed
You changed active_aoi
the maps in ch04 are for the old area and would be skipped as done
use a new mapset (change HERE) or a new project for the new area
References
Allen, R.G., Pereira, L.S., Raes, D., Smith, M. (1998). Crop evapotranspiration: Guidelines for computing crop water requirements. FAO Irrigation and Drainage Paper 56. https://www.fao.org/4/x0490e/x0490e00.htm
de Wit, A. PCSE: Python Crop Simulation Environment, pcse/util.py (master branch, read 2026-11-28): https://github.com/ajwdewit/pcse
Hobbins, M. T., A. Wood, D. J. McEvoy, J. L. Huntington, C. Morton, M. Anderson and C. Hain (2016). The Evaporative Demand Drought Index. Part I: Linking drought evolution to variations in evaporative demand. Journal of Hydrometeorology 17(6), 1745-1761. https://doi.org/10.1175/JHM-D-15-0121.1