Skip to main content

Chapter 3: Importing the Record and Checking It

Tutorial series: Climate Analysis with GRASS and Python

Chapter 3: Importing the Record and Checking It

TipAt a glance
  • You will build: six GRASS time series over a rectangle around Nusa Tenggara Timur (NTT), one per AgERA5 variable that later chapters need (Tmax, Tmin, dew point, 10 m wind, solar radiation and AgERA5’s own reference evapotranspiration), with one map per day, units and labels on every map, and a table of quality checks.
  • Two sizes: by default the chapter imports the teaching years 2015 and 2016 (731 days, a leap year included). With run_full: true in config.yml it imports 1979-2025: 17,167 days and 103,002 maps. Chapters 4 and 5 need the full record, because EDDI compares each date with a long baseline of the same season (this series uses 1991-2020 for now, baseline in config.yml).
  • You need: Chapters 1 and 2; a CDS account (Chapter 1) or a local AgERA5 archive; and paths.staged set in config.yml (see Setup).
  • Time and disk: when tested on Windows 11 with 8 of 80 logical CPUs in use, the teaching years took 453 s from a local archive and 538 s from CDS downloads already on disk (the 10 downloads took about 40 minutes more). The full record took 3,626 s, about an hour, from the archive. The full record uses 771 MB in 1,339,030 files in the GRASS mapset, plus 392 MB of prepared files; the teaching years about 33 MB and 17 MB. The outputs shown are from the full run; the checkpoint prints your own time and disk. The preview figures after each step add about 14 s; they were drawn in a later run on the same finished mapsets, so the times above leave them out.
NoteLearning objectives

After this chapter you can:

  1. Plan a large job: time each step on one variable-year, extrapolate to the full record, and compare the estimate with the run.
  2. Prepare data so GRASS reads each source once: one small file per variable and year for your area.
  3. Import, rename, label and register thousands of maps with a pipeline you can stop and restart without redoing finished years.
  4. Read a time series that lives in another mapset.
  5. Check a long record for missing days, a changing land mask, physically impossible values and disagreement between variables, using what GRASS already stores where you can.

Setup

Before running, open config.yml and set paths.staged, which is new in this chapter, to a folder outside OneDrive next to downloads. It holds one small NetCDF per variable-year (17 MB for the teaching years when tested). The setup cell refuses a relative path or one inside OneDrive, as Chapter 1 explained.

The raw inputs go into their own mapset, agera5, which Chapters 4 and 5 will read from, so a later chapter can be re-run or deleted without touching 47 years of imports. Chapter 1’s plan puts all six variables in this one mapset rather than one mapset per variable. The reason: when tested, pygrass could set units only on maps in the mapset the kernel started in (section 7), and one mapset keeps that simple. The checks at the end run from a second mapset, ch03. Both are new, so no mask can be left over and the mask removal of Chapter 2 is not needed.

One line in the cell undoes a default. grass.jupyter.init() sets GRASS_OVERWRITE=1 for this process and every tool it starts, so any tool may replace an existing map or dataset without being asked (grass.jupyter). Chapters 1 and 2 relied on it without harm, because each cell there recreated its own small data. Here it is dangerous: when tested, a t.create with no overwrite option replaced an existing dataset and unregistered all its maps. With the default undone, every overwrite in this chapter is asked for with overwrite=True.

RUN_FULL comes from config.yml. Leave it false until the teaching run has worked once.

import datetime as dt
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path

CHAPTER_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 agera5
from pgca import session as pg

cfg = pg.load_config(ROOT / "config.yml")
RAW = "agera5"     # raw inputs; Chapters 4 and 5 read them from here
CHECKS = "ch03"   # this chapter's quality checks
session = pg.start(cfg, mapset=RAW)
os.environ["GRASS_OVERWRITE"] = "0"  # grass.jupyter turns overwriting on for every tool

import grass.script as gs
import numpy as np
import pandas as pd
import xarray as xr
from grass.pygrass.gis.region import Region
from grass.pygrass.modules import Module, ParallelModuleQueue
from grass.pygrass.raster import RasterRow
from grass.pygrass.raster.abstract import Info

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))
YEARS = FULL_YEARS if RUN_FULL else list(range(cfg["teaching_years"][0], cfg["teaching_years"][1] + 1))
VARS = list(cfg["agera5"]["variables"])
NC = {v: spec["nc"] for v, spec in cfg["agera5"]["variables"].items()}
NPROCS = min(8, os.cpu_count() or 1)
STAGED = pg.check_data_path(cfg["paths"]["staged"])
DL_DIR = pg.check_data_path(cfg["paths"]["downloads"]) / "agera5"
OUT_DIR = pg.check_data_path(cfg["paths"]["outputs"]) / "ch03"
OUT_DIR.mkdir(parents=True, exist_ok=True)

assert cfg["period"]["start"].endswith("-01-01") and cfg["period"]["end"].endswith("-12-31"), "use whole years"
print("Mapset:", gs.gisenv()["MAPSET"], "| area:", AOI_NAME, "| years:", YEARS[0], "to", YEARS[-1], "| full run:", RUN_FULL)
print("Variables:", VARS, "| parallel processes:", NPROCS)
Mapset: agera5 | area: ntt | years: 1979 to 2025 | full run: True
Variables: ['tmax', 'tmin', 'tdew', 'ws10', 'srad', 'et0'] | parallel processes: 8

Helpers used throughout. days_of() lists the days of a year, and map_names() gives the GRASS name of every daily map of one variable-year, <variable>_<YYYYMMDD> as in Chapter 2. present() lists the maps already in agera5, which is how every step below knows what is already done. search_path() returns the mapsets GRASS looks in, parsed from JSON, the format the g.mapsets manual recommends for scripts.

def days_of(year):
    n = (dt.date(year + 1, 1, 1) - dt.date(year, 1, 1)).days
    return [dt.date(year, 1, 1) + dt.timedelta(days=i) for i in range(n)]


def map_names(var, year):
    return [f"{var}_{d:%Y%m%d}" for d in days_of(year)]


def present(pattern="*"):
    return {n.split("@")[0] for n in gs.list_strings("raster", pattern=pattern, mapset=RAW)}


def search_path():
    return gs.parse_command("g.mapsets", flags="p", format="json")["mapsets"]

1. Size up the job

Before running anything long, count what has to exist at the end. The full record is the number to plan for even if you start with the teaching years.

def n_maps(years):
    return sum(len(days_of(y)) for y in years)


source = {v: "archive" if all(agera5.archive_file(cfg, v, y) for y in YEARS) else "CDS download" for v in VARS}
plan = pd.DataFrame({
    "variable": VARS,
    "NetCDF variable": [NC[v] for v in VARS],
    "source": [source[v] for v in VARS],
    "maps this run": [n_maps(YEARS) for _ in VARS],
})
print(plan.to_string(index=False))
print(f"\nThis run: {len(VARS) * len(YEARS)} variable-years, {len(VARS) * n_maps(YEARS):,} maps")
print(f"Full record: {len(VARS) * len(FULL_YEARS)} variable-years, {len(VARS) * n_maps(FULL_YEARS):,} maps")
variable                   NetCDF variable  source  maps this run
    tmax        Temperature_Air_2m_Max_24h archive          17167
    tmin        Temperature_Air_2m_Min_24h archive          17167
    tdew Dew_Point_Temperature_2m_Mean_24h archive          17167
    ws10           Wind_Speed_10m_Mean_24h archive          17167
    srad              Solar_Radiation_Flux archive          17167
     et0  ReferenceET_PenmanMonteith_FAO56 archive          17167

This run: 282 variable-years, 103,002 maps
Full record: 282 variable-years, 103,002 maps

2. Get the data

If paths.agera5_archive points to a local copy of AgERA5, every variable-year is read from it and this section does nothing. Otherwise each variable-year is one CDS request of the kind Chapter 2 made: a whole year, cut to the area on the server, delivered as a zip of daily files. The zips from Chapter 2 (Tmax and Tmin 2015) are reused, so the teaching years need 10 new requests and the full record 280.

When tested, the 10 teaching requests took about 40 minutes in all, 3.0 to 6.6 minutes each including the time in the CDS queue, and each zip held 10.6 to 11.0 MB for one variable-year of NTT. At that pace the full record’s 280 requests take about 19 hours and about 3 GB of zips; this is an extrapolation, not a measured full download. Requests run one after another; running several at once was not tested.

The next cell submits one CDS request per variable-year that is not yet on disk. If it is interrupted, run it again: finished years are skipped, and a download that was cut off is started again (each download is written under a temporary name until it is complete). It also unzips every zip it uses, including the reused ones.

need = [(v, y) for v in VARS for y in YEARS if agera5.archive_file(cfg, v, y) is None]
DL_DIR.mkdir(parents=True, exist_ok=True)
for v, y in need:  # reuse Chapter 2's zips (Tmax and Tmin 2015)
    name = f"agera5_{v}_{y}_{AOI_NAME}.zip"
    earlier = Path(cfg["paths"]["downloads"]) / "ch02" / name
    if earlier.exists() and not (DL_DIR / name).exists():
        shutil.copy2(earlier, DL_DIR / name)
todo = [(v, y) for v, y in need if not (DL_DIR / f"agera5_{v}_{y}_{AOI_NAME}.zip").exists()]
print(f"{len(need)} variable-years have no archive file; {len(todo)} need a CDS request")

t0 = time.time()
for v, y in need:
    agera5.download_year(cfg, v, y, AOI_NAME, DL_DIR)  # downloads only if the zip is missing; always unzips
    if (v, y) in todo:
        print(f"  {todo.index((v, y)) + 1}/{len(todo)} {v} {y} downloaded after {time.time() - t0:.0f} s")
0 variable-years have no archive file; 0 need a CDS request

3. One file per day, or one file per year?

Chapter 2 imported one map per r.in.gdal call. Repeated 103,002 times, the cost of each call decides whether the import takes minutes or hours, so measure it before committing.

Every single-day call is a new process that opens its file again. From the archive there is a second cost: the yearly files checked were compressed in blocks of 31 days by 200 by 400 cells, so reading one day decompresses the whole 31-day block around it (two blocks side by side for NTT), and because each day is read by a separate process, that happens again for every day of the block. The alternative is to prepare each variable-year first: cut your area out of the source in one read (or stack the year’s daily CDS files) into one small NetCDF, then import all its days with one r.in.gdal call.

The cell times both routes on the first variable-year: 31 single-day imports run NPROCS at a time, against preparing and importing the whole year. The test maps are deleted afterwards (a multi-band import also makes an imagery group, explained in section 5).

v, y = VARS[0], YEARS[0]
sources = agera5.daily_sources(cfg, v, y, DL_DIR / f"{v}_{y}_{AOI_NAME}")[:31]
assert len(sources) == 31, f"no daily files for {v} {y}: run section 2 first"
t0 = time.time()
queue = ParallelModuleQueue(nprocs=NPROCS)
for d, inp, band in sources:
    queue.put(Module("r.in.gdal", input=inp, band=band, output=f"timing_{d:%Y%m%d}", flags="r",
                     overwrite=True, quiet=True, run_=False))
queue.wait()
per_day = (time.time() - t0) / len(sources)

scratch = STAGED / "_timing"
shutil.rmtree(scratch, ignore_errors=True)
t0 = time.time()
f = agera5.stage_year(cfg, v, y, AOI_NAME, scratch, DL_DIR)
t_stage = time.time() - t0
t0 = time.time()
Module("r.in.gdal", input=agera5.gdal_name(f, NC[v]), output=f"timing_{y}", flags="rk", overwrite=True, quiet=True)
t_import = time.time() - t0
Module("g.remove", type="raster", pattern="timing_*", flags="f", quiet=True)
Module("g.remove", type="group", pattern="timing_*", flags="f", quiet=True)
shutil.rmtree(scratch)

full_vy, full_maps = len(VARS) * len(FULL_YEARS), len(VARS) * n_maps(FULL_YEARS)
est_days, est_years = per_day * full_maps, (t_stage + t_import) * full_vy
print(f"single days, {NPROCS} at a time: {per_day:.2f} s per map -> full record about {est_days / 3600:.1f} h")
print(f"prepare {t_stage:.1f} s + import {t_import:.1f} s per variable-year, one at a time "
      f"-> full record about {est_years / 3600:.1f} h ({est_days / est_years:.0f} times less)")
single days, 8 at a time: 0.32 s per map -> full record about 9.2 h
prepare 3.8 s + import 7.3 s per variable-year, one at a time -> full record about 0.9 h (11 times less)

The second route is the one printed as many times faster, and both data sources end up as the same kind of small yearly file, so the rest of the chapter uses it for both. Both estimates leave out renaming, labelling and registration, which section 6 times.

The helper that prepares the files, agera5.stage_year() in src/pgca/agera5.py, is short enough to read. From the archive it selects cell centres by nearest match, as Chapter 1 showed you must (slicing with floats silently drops edge rows and columns). From CDS downloads it stacks the daily files in date order. It then checks that the file holds every day of the year in order, at the expected 32 by 64 cells, and writes under a temporary name first, so an interrupted run never leaves a file that looks finished.

4. Prepare every variable-year

One file per variable-year, one at a time; files already prepared are checked and skipped. When tested, the teaching years took 14 s from the archive and 102 s from CDS downloads (stacking 365 or 366 small files per variable-year), and the full record 336 s from the archive.

before = {(v, y) for v in VARS for y in YEARS if agera5.staged_path(STAGED, v, y, AOI_NAME).exists()}
t0 = time.time()
staged = {}
for v in VARS:
    for y in YEARS:
        staged[v, y] = agera5.stage_year(cfg, v, y, AOI_NAME, STAGED, DL_DIR)
t_stage_all = time.time() - t0
mb = sum(p.stat().st_size for p in staged.values()) / 1e6
print(f"{len(staged) - len(before)} files prepared, {len(before)} already there, {t_stage_all:.0f} s; "
      f"{mb:.1f} MB in {STAGED}")
282 files prepared, 0 already there, 336 s; 391.8 MB in E:\temp\pgca\staged

Units travel with the data. Rather than typing them, read the units attribute each file carries, and check that it is the same in every year:

UNITS = {}
for v in VARS:
    seen = set()
    for y in YEARS:
        with xr.open_dataset(staged[v, y]) as ds:
            seen.add(ds[NC[v]].attrs.get("units"))
    assert len(seen) == 1 and None not in seen, f"{v}: units differ between years or are missing: {seen}"
    UNITS[v] = seen.pop()
print(UNITS)
{'tmax': 'K', 'tmin': 'K', 'tdew': 'K', 'ws10': 'm s-1', 'srad': 'J m-2 d-1', 'et0': 'mm d-1'}

Look before moving on. Before importing anything, draw one day of a prepared file, Tmax and Tmin on one colour scale, read with xarray, since GRASS has not seen these files yet. A correct file shows the islands with values, the sea empty (null, drawn white) and north at the top, and the Tmin summary line lower than the Tmax one. A map upside down, shifted by a row or column, or filled over the sea would mean the cut-out went wrong, and every map imported from it in section 5 would carry the error.

The cell picks one day, PREVIEW_DAY, in a year that both the teaching run and the full run import; later previews draw the same day.

from pgca import preview

first = cfg["teaching_years"][0]
PREVIEW_DAY = dt.date(first if first in YEARS else YEARS[0], 7, 15)  # reused by the previews below
k = (PREVIEW_DAY - dt.date(PREVIEW_DAY.year, 1, 1)).days
day_arrays = []
for v in ["tmax", "tmin"]:
    with xr.open_dataset(staged[v, PREVIEW_DAY.year]) as ds:
        day_arrays.append(ds[NC[v]].values[k])
preview.array_maps(day_arrays, [f"{v} {PREVIEW_DAY}, prepared file" for v in ["tmax", "tmin"]], UNITS["tmax"],
                   extent=preview.region_extent());

tmax 2015-07-15, prepared file: 2,048 cells, 935 null; min 294.14, mean 299.89, max 304.89 K
tmin 2015-07-15, prepared file: 2,048 cells, 935 null; min 286.27, mean 296.06, max 300.32 K

Both summary lines should count the same cells and the same nulls: the land mask is the same in both files. Section 5 draws this day again, read back from GRASS.

5. Import, rename and label

Three steps per variable-year, each in its own cell:

  1. Import: one r.in.gdal -rk call per file, NPROCS files at a time, the route section 3 measured. A multi-band import names its maps after the bands; -k makes that the band number, tmax_2015.1 to tmax_2015.365, whatever band names the file carries.
  2. Rename to tmax_20150101 and so on, with one g.rename call per year that takes a list of old and new names, instead of one call (and one process) per map.
  3. Label: semantic label and units set in this Python process with pygrass Info, as in Chapter 2, where it was about 70 times faster than one r.support call per map.

A variable-year counts as done when all its daily maps exist and the last of them has its units set. Labels run in date order and each map gets its label before its units, so a year interrupted half-way shows up as not done and is redone. When tested, the three steps took 53 s for the teaching years and 1,212 s, about 20 minutes (import 721 s, rename 262 s, labels 229 s) on the full record.

def year_done(v, y, have):
    names = map_names(v, y)
    return set(names) <= have and Info(names[-1], RAW).units == UNITS[v]


have = present()
to_import = [(v, y) for v in VARS for y in YEARS if not year_done(v, y, have)]
print(f"{len(to_import)} of {len(VARS) * len(YEARS)} variable-years to import")

t0 = time.time()
queue = ParallelModuleQueue(nprocs=NPROCS)
for v, y in to_import:
    queue.put(Module("r.in.gdal", input=agera5.gdal_name(staged[v, y], NC[v]), output=f"{v}_{y}",
                     flags="rk", overwrite=True, quiet=True, run_=False))
queue.wait()
t_import_all = time.time() - t0
print(f"imported in {t_import_all:.0f} s")
282 of 282 variable-years to import
imported in 721 s

When tested, a multi-band import also recorded its maps as an imagery group: a named list of maps that the GRASS imagery tools take as one input (i.group). Nothing here needs them, so the groups this run made are removed after renaming.

t0 = time.time()
queue = ParallelModuleQueue(nprocs=NPROCS)
for v, y in to_import:
    pairs = []
    for band, name in enumerate(map_names(v, y), start=1):
        pairs += [f"{v}_{y}.{band}", name]
    queue.put(Module("g.rename", raster=pairs, overwrite=True, quiet=True, run_=False))
queue.wait()
ours = {f"{v}_{y}" for v, y in to_import} & {g.split("@")[0] for g in gs.list_strings("group", mapset=RAW)}
if ours:
    Module("g.remove", type="group", name=sorted(ours), flags="f", quiet=True)
t_rename = time.time() - t0
print(f"renamed in {t_rename:.0f} s")
renamed in 262 s
t0 = time.time()
for v, y in to_import:
    for name in map_names(v, y):
        info = Info(name, RAW)
        info.semantic_label = v
        info.units = UNITS[v]  # last: units mark the map as finished
t_label = time.time() - t0

have = present()
missing = [(v, y) for v in VARS for y in YEARS if not year_done(v, y, have)]
leftover = present("*.*")
print(f"labelled in {t_label:.0f} s | variable-years complete: {len(VARS) * len(YEARS) - len(missing)} of "
      f"{len(VARS) * len(YEARS)} | band-named maps left over: {len(leftover)}")
assert not missing and not leftover, "re-run the three cells of this section"
labelled in 229 s | variable-years complete: 282 of 282 | band-named maps left over: 0

Look before moving on. Read PREVIEW_DAY back from GRASS, one map per variable. Each title carries the units stored on the map itself, read with Info, not taken from the UNITS table, so a title without units would show a map the label step missed. Variables with the same units share one colour scale: the three temperatures are drawn together, and wind, radiation and reference ET get one figure each. Check that the tmax line matches the prepared-file line printed in section 4 for the same day, that the null count is the same in every map (the sea), that dew point sits below Tmax, and that wind, radiation and reference ET are zero or positive. If one variable looks wrong, re-run the three cells of this section for it before registering anything.

day = f"{PREVIEW_DAY:%Y%m%d}"
for u in dict.fromkeys(UNITS[v] for v in VARS):  # one figure per unit, so each scale has one meaning
    names = [f"{v}_{day}" for v in VARS if UNITS[v] == u]
    preview.maps(names, [f"{n} ({Info(n, RAW).units})" for n in names], u, panel_width=3.6 if len(names) > 1 else 4.5)

tmax_20150715 (K): 2,048 cells, 935 null; min 294.14, mean 299.89, max 304.89 K
tmin_20150715 (K): 2,048 cells, 935 null; min 286.27, mean 296.06, max 300.32 K
tdew_20150715 (K): 2,048 cells, 935 null; min 283.53, mean 291.65, max 295.14 K

ws10_20150715 (m s-1): 2,048 cells, 935 null; min 0.95, mean 4.96, max 10.02 m s-1

srad_20150715 (J m-2 d-1): 2,048 cells, 935 null; min 15373594.00, mean 19631709.77, max 22849610.00 J m-2 d-1

et0_20150715 (mm d-1): 2,048 cells, 935 null; min 2.94, mean 4.64, max 6.26 mm d-1

6. Register the time series

One space-time raster dataset (STRDS) per variable, named after it: tmax, tmin, tdew, ws10, srad, et0. Its semantic type, set per variable in config.yml, records what each value is: max for Tmax, min for Tmin, mean for daily means (dew point, wind), and sum for daily totals (radiation in J m-2 per day, reference ET in mm per day). Treat it as description: neither the t.create nor the t.rast.aggregate manual says the type is used, and in the GRASS 8.5.0 source t.rast.aggregate takes only its method= (default average), so an aggregate still needs its method chosen by you.

One rule from Chapter 2 and one new one. Register with fully qualified names (tmax_20150101@agera5): bare names cost a lookup per map, about four times slower when tested. And never re-create a full dataset with t.create --overwrite, which unregisters every map it held. So the cell creates a dataset only if it is missing, asks it which maps it already holds, and registers only the rest.

Two repairs make the cell safe to re-run. t.register writes the map rows first and the dataset’s summary (number of maps, extent, minimum and maximum) at the end, so an interrupted registration can leave the summary stale; the cell compares it with the registered maps and rebuilds it with t.support -u if they disagree. And if section 5 re-imported a year that was already registered, t.support -m refreshes the stored values of those maps.

Slow cell: when tested, about 35 s per variable for the teaching years and 1,610 s, about 27 minutes (about 16 ms per map) on the full record.

def registered(strds):
    out = json.loads(gs.read_command("t.rast.list", input=strds, columns="name", format="json"))
    return {row["name"] for row in out["data"]}


existing_strds = {s.split("@")[0] for s in gs.read_command("t.list", type="strds", where=f"mapset = '{RAW}'").split()}
t0 = time.time()
for v in VARS:
    if v not in existing_strds:
        Module("t.create", output=v, type="strds", temporaltype="absolute",
               semantictype=cfg["agera5"]["variables"][v]["semantic"],
               title=f"AgERA5 {NC[v]}", description=f"AgERA5 v{cfg['agera5']['version']} {NC[v]}, {AOI_NAME}, daily")
    done = registered(v)
    todo = [n for y in YEARS for n in map_names(v, y) if n not in done]
    refreshed = [n for vv, y in to_import if vv == v for n in map_names(v, y) if n in done]
    if todo:
        reg_file = OUT_DIR / f"register_{v}.txt"
        with reg_file.open("w") as f:
            for n in todo:
                d = dt.datetime.strptime(n[-8:], "%Y%m%d").date()
                f.write(f"{n}@{RAW}|{d}|{d + dt.timedelta(days=1)}\n")
        Module("t.register", input=v, type="raster", file=str(reg_file), quiet=True)
    if refreshed:
        Module("t.support", input=v, flags="m", quiet=True)
    if int(gs.parse_command("t.info", input=v, flags="g")["number_of_maps"]) != len(registered(v)):
        Module("t.support", input=v, flags="u", quiet=True)
        print(f"{v}: dataset summary was stale and has been rebuilt")
    print(f"{v}: registered {len(todo)} maps, {time.time() - t0:.0f} s so far")
t_register = time.time() - t0
tmax: registered 17167 maps, 265 s so far
tmin: registered 17167 maps, 521 s so far
tdew: registered 17167 maps, 802 s so far
ws10: registered 17167 maps, 1081 s so far
srad: registered 17167 maps, 1386 s so far
et0: registered 17167 maps, 1610 s so far
rows = []
for v in VARS:
    info = gs.parse_command("t.info", input=v, flags="g")
    rows.append({"dataset": v, "maps": int(info["number_of_maps"]), "start": info["start_time"].strip("'")[:10],
                 "end": info["end_time"].strip("'")[:10], "semantic type": info["semantic_type"].strip("'"),
                 "min": float(info["min_min"]), "max": float(info["max_max"]), "units": UNITS[v]})
datasets = pd.DataFrame(rows)
print(datasets.to_string(index=False, float_format="{:.6g}".format))
dataset  maps      start        end semantic type      min         max     units
   tmax 17167 1979-01-01 2026-01-01           max  289.555     312.551         K
   tmin 17167 1979-01-01 2026-01-01           min  284.188     302.987         K
   tdew 17167 1979-01-01 2026-01-01          mean  273.972     299.525         K
   ws10 17167 1979-01-01 2026-01-01          mean        0     19.5824     m s-1
   srad 17167 1979-01-01 2026-01-01           sum        0 3.04365e+07 J m-2 d-1
    et0 17167 1979-01-01 2026-01-01           sum 0.383761      8.2752    mm d-1

Two things to read in this table. end is the end of the last map’s interval: the last day runs until midnight, which is the start of the next day (Chapter 2, section 6). And the min and max columns are not computed by this cell: the temporal database stored each map’s minimum and maximum when it was registered, and t.info reports the extremes over the dataset. Section 8 uses the same stored values to check every map.

Look before moving on. The temporal database is now the index that later chapters search by date. Look at what it holds for one year of tmax: for each registered map, its date and the lowest and highest Tmax over land that day, listed from the database with a where condition on start_time, without opening a single map. A correct registration gives one value per day of the year in each series, the maximum above the minimum every day, both inside the min and max of the table above, and a gradual change through the seasons. A gap, a jump on a single day, or values typical of another variable would mean a map was registered under the wrong date or name.

yr = PREVIEW_DAY.year
out = json.loads(gs.read_command("t.rast.list", input="tmax", columns=["name", "start_time", "min", "max"],
                                 where=f"start_time >= '{yr}-01-01' AND start_time < '{yr + 1}-01-01'", format="json"))
stored = pd.DataFrame(out["data"])
preview.series(pd.to_datetime(stored["start_time"]),
               {"lowest Tmax over land": stored["min"].astype(float), "highest Tmax over land": stored["max"].astype(float)},
               UNITS["tmax"], title=f"tmax maps registered for {yr}: minimum and maximum stored for each map");

lowest Tmax over land: 365 values, 0 null; min 292.67, mean 296.30, max 299.82 K
highest Tmax over land: 365 values, 0 null; min 302.79, mean 305.79, max 310.07 K

Now compare the plan from section 3 with what happened. The estimate covered preparing and importing, one file at a time; the import actually ran NPROCS at a time, and three steps were not in the estimate at all:

n_vy, n_new = len(VARS) * len(YEARS), len(to_import)
steps = pd.DataFrame([
    {"step": "prepare + import", "estimated s": round((t_stage + t_import) * n_vy), "actual s": round(t_stage_all + t_import_all)},
    {"step": "rename", "estimated s": None, "actual s": round(t_rename)},
    {"step": "units and labels", "estimated s": None, "actual s": round(t_label)},
    {"step": "register", "estimated s": None, "actual s": round(t_register)},
])
print(steps.to_string(index=False))
print(f"variable-years done in this run: {n_new} of {n_vy} (finished ones are skipped and cost nothing here)")
            step  estimated s  actual s
prepare + import       3133.0      1057
          rename          NaN       262
units and labels          NaN       229
        register          NaN      1610
variable-years done in this run: 282 of 282 (finished ones are skipped and cost nothing here)

7. Working from another mapset

Chapters 4 and 5 will work in their own mapsets and read these inputs. Do the same here: move to a new mapset ch03 for the checks.

From here on the kernel is in ch03. To re-run anything above, or after changing config.yml, restart the kernel and run from Setup. Finished work is skipped, so this costs little.

session.switch_mapset() changes the mapset for every GRASS tool started from now on: t.rast.list, r.mapcalc and the rest run in ch03. It does not change pygrass code that runs inside this Python process. When tested, after the switch pygrass still treated agera5 as the current mapset: setting units with Info on an agera5 map still worked, and a map written with RasterRow landed in agera5, not ch03. Reading is unaffected, because you name the mapset. So the switch protects agera5 from tools, not from in-process writes. This chapter does its in-process writing (section 5) before the switch and only reads afterwards; Chapters 4 and 5, which write with pygrass, start their kernel in their own mapset instead.

Each mapset has its own region, and a new one starts from the project default, so set it again after switching:

pg.ensure_mapset(PROJECT, CHECKS)
session.switch_mapset(CHECKS)
Module("g.region", n=AOI["n"], s=AOI["s"], w=AOI["w"], e=AOI["e"], res=cfg["res"])
print("now in:", gs.gisenv()["MAPSET"], "| search path:", search_path())
now in: ch03 | search path: ['ch03', 'PERMANENT']

Maps in another mapset can be read by their full name (tmax_20150101@agera5) at any time, but the temporal tools only open the temporal database of a mapset that is on the search path. This call is meant to fail the first time. The cell catches what GRASS prints and shows its error line; GRASS also creates ch03’s own temporal database here, as it does in every mapset the first time a t.* tool runs there. On a re-run the path is already set and the call succeeds.

p = gs.start_command("t.rast.list", input=f"tmax@{RAW}", columns="name", format="json",
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
_, err = p.communicate()
if p.returncode:
    msg = gs.decode(err)
    print(f"t.rast.list tmax@{RAW} failed (exit code {p.returncode}). GRASS said:")
    print(" ".join(msg[msg.find("ERROR"):].split()))
else:
    print(f"t.rast.list tmax@{RAW} worked: {RAW} is already on the search path")
t.rast.list tmax@agera5 failed (exit code 1). GRASS said:
ERROR: Unable to execute sql statement. You have no permission to access mapset <agera5>, or mapset <agera5> has no temporal database. Accessible mapsets are: <ch03>

Add agera5 to the search path. The setting is stored in ch03, so it persists:

Module("g.mapsets", operation="add", mapset=RAW)
print("search path:", search_path())
first = json.loads(gs.read_command("t.rast.list", input=f"tmax@{RAW}", columns=["name", "start_time"], format="json"))
print(f"first maps of tmax@{RAW}:", [row["name"] for row in first["data"][:3]])
search path: ['ch03', 'PERMANENT', 'agera5']
first maps of tmax@agera5: ['tmax_19790101', 'tmax_19790102', 'tmax_19790103']

8. Quality checks

A long record can be wrong in ways a single map never shows: a day missing, an import that went wrong for one year, a land mask that changes, a value no instrument could give, or two variables that contradict each other. Reading all 103,002 maps from GRASS would be slow: when tested, pygrass RasterRow took about 41 ms per map (about 70 minutes in all) and t.rast.univar with nprocs=8 about 79 ms (about 2.3 hours). So the checks take each answer from the cheapest place that holds it:

  • What is registered, and each map’s minimum and maximum: already in the temporal database (t.rast.list).
  • Cell-by-cell checks: from the prepared yearly files with numpy, one year at a time so memory stays small for larger areas. Two checks below confirm that the GRASS maps match these files.
def listing(v):
    out = json.loads(gs.read_command("t.rast.list", input=f"{v}@{RAW}",
                                     columns=["name", "start_time", "min", "max"], format="json"))
    df = pd.DataFrame(out["data"])
    df["date"] = pd.to_datetime(df["start_time"]).dt.date
    return df


lists = {v: listing(v) for v in VARS}
expected = {d for y in YEARS for d in days_of(y)}
for v, df in lists.items():
    dates = set(df["date"])
    print(f"{v}: {len(expected & dates)} of {len(expected)} expected days registered, "
          f"{len(expected - dates)} missing, {len(df) - df['date'].nunique()} duplicates")
tmax: 17167 of 17167 expected days registered, 0 missing, 0 duplicates
tmin: 17167 of 17167 expected days registered, 0 missing, 0 duplicates
tdew: 17167 of 17167 expected days registered, 0 missing, 0 duplicates
ws10: 17167 of 17167 expected days registered, 0 missing, 0 duplicates
srad: 17167 of 17167 expected days registered, 0 missing, 0 duplicates
et0: 17167 of 17167 expected days registered, 0 missing, 0 duplicates

Look before moving on. The listings just made hold every registered map with its date, so the number of maps per year comes from them with no further call to GRASS. Every year should have as many maps as it has days (366 in a leap year, 365 otherwise), and all six variables the same count. A year with a missing or extra map shows as a bar that does not reach its tick, or one that passes it, and the printed line counts such years.

import matplotlib.pyplot as plt

per_year = pd.DataFrame({v: pd.to_datetime(df["start_time"]).dt.year.value_counts().sort_index()
                         for v, df in lists.items()})
days_in_year = pd.Series({y: len(days_of(y)) for y in sorted(set(per_year.index) | set(YEARS))})
fig, ax = plt.subplots(figsize=(9, 2.8), constrained_layout=True)
ax.bar(per_year.index, per_year[VARS[0]], color="0.7", label=f"{VARS[0]} maps")
ax.plot(days_in_year.index, days_in_year.values, "k_", ms=10, mew=1.5, label="days in the year")
ax.set_ylim(days_in_year.min() - 5, days_in_year.max() + 2)
ax.set_ylabel("maps (axis starts at 360)" if days_in_year.min() == 365 else "maps", fontsize=9)
ax.legend(fontsize=8, frameon=False, loc="lower right")
ax.tick_params(labelsize=8)
plt.show()
off = per_year.reindex(days_in_year.index).ne(days_in_year, axis=0).any(axis=1)
same = per_year.eq(per_year[VARS[0]], axis=0).all().all()
print(f"{len(per_year)} years, {per_year.values.min()} to {per_year.values.max()} maps per year and variable; "
      f"years where a count differs from the days in the year: {int(off.sum())}; "
      f"all variables have the same count every year: {bool(same)}")

47 years, 365 to 366 maps per year and variable; years where a count differs from the days in the year: 0; all variables have the same count every year: True

Now the cell-by-cell pass. For every variable and day it records the minimum, maximum and mean over land, the number of valid cells, whether the valid cells are exactly those of the first Tmax map (AgERA5 covers land only, so this is the land mask), and how many cells are negative or exactly zero. It also compares variables cell by cell, for two things that should not happen physically:

  • Tmin above Tmax: the day’s minimum temperature above its maximum.
  • Dew point above Tmax: the dew point is the temperature at which the air would be saturated, which places it at or below the air temperature, so a daily mean dew point above the day’s maximum temperature should not occur. (This series has not yet checked that definition against a primary source.)

Each case is kept with its date, cell and size. For NTT the land mask should have 1,113 of the 2,048 cells, the count of non-null cells in Chapter 2.

lat, lon = agera5.aoi_centres(AOI, cfg["res"])
daily, flags = [], []
land = None
t0 = time.time()
for y in YEARS:
    arr = {}
    for v in VARS:
        with xr.open_dataset(staged[v, y]) as ds:
            arr[v] = ds[NC[v]].values
    if land is None:
        land = ~np.isnan(arr["tmax"][0])
    for v, a in arr.items():
        valid = ~np.isnan(a)
        daily.append(pd.DataFrame({
            "variable": v, "date": days_of(y),
            "min": np.nanmin(a, axis=(1, 2)), "max": np.nanmax(a, axis=(1, 2)), "mean": np.nanmean(a, axis=(1, 2)),
            "valid": valid.sum(axis=(1, 2)), "same_land": (valid == land).all(axis=(1, 2)),
            "negative": (a < 0).sum(axis=(1, 2)), "zero": (a == 0).sum(axis=(1, 2))}))
    for check, high, low in [("tmin above tmax", "tmin", "tmax"), ("tdew above tmax", "tdew", "tmax")]:
        excess = arr[high] - arr[low]
        for t, i, j in np.argwhere(excess > 0):
            flags.append({"check": check, "date": days_of(y)[t], "lat": lat[i], "lon": lon[j],
                          "excess_K": float(excess[t, i, j])})
daily = pd.concat(daily, ignore_index=True)
flags = pd.DataFrame(flags, columns=["check", "date", "lat", "lon", "excess_K"])
print(f"{len(daily):,} variable-days checked in {time.time() - t0:.0f} s; land cells: {int(land.sum())} of {land.size}")
103,002 variable-days checked in 15 s; land cells: 1113 of 2048

Did the import keep every value? Compare each GRASS map’s stored minimum and maximum with the same day in the prepared file. This covers every map at no extra cost; a map imported from the wrong band, or with the wrong date, would almost certainly differ. The temporal database stores the minimum and maximum rounded to six decimals, so the comparison allows a difference of 1e-6 in the variable’s own units plus one part in a million of the value (that is how np.isclose combines its two tolerances). Without the absolute part, 48 of 731 wind maps, with daily minima near 0.17 m s-1, failed on rounding alone when tested.

mismatch = {}
for v in VARS:
    both = lists[v].merge(daily[daily["variable"] == v], on="date", suffixes=("_grass", "_file"))
    close = dict(rtol=1e-6, atol=1e-6)
    ok = np.isclose(both["min_grass"], both["min_file"], **close) & np.isclose(both["max_grass"], both["max_file"], **close)
    mismatch[v] = int((~ok).sum())
    print(f"{v}: {len(both)} maps compared, {mismatch[v]} differ")
tmax: 17167 maps compared, 0 differ
tmin: 17167 maps compared, 0 differ
tdew: 17167 maps compared, 0 differ
ws10: 17167 maps compared, 0 differ
srad: 17167 maps compared, 0 differ
et0: 17167 maps compared, 0 differ

Minimum and maximum do not see the null pattern, so also read a sample of maps cell by cell from GRASS: one day per variable-year, chosen at random with a fixed seed so the run is repeatable.

Region().set_raster_region()  # in-process reads use the region pygrass last saw (Chapter 2, section 4)
rng = np.random.default_rng(3)
sample_bad = 0
for v in VARS:
    for y in YEARS:
        k = int(rng.integers(len(days_of(y))))
        with RasterRow(map_names(v, y)[k], mapset=RAW) as rr:
            g = np.array([np.array(row, dtype="float32") for row in rr])
        with xr.open_dataset(staged[v, y]) as ds:
            f = ds[NC[v]].values[k]
        assert g.shape == f.shape, f"read {g.shape} cells, expected {f.shape}"
        sample_bad += not np.array_equal(g, f, equal_nan=True)
print(f"{len(VARS) * len(YEARS)} sampled maps read from GRASS, {sample_bad} differ from the prepared files")
282 sampled maps read from GRASS, 0 differ from the prepared files

The summary table, one row per variable. negative cell-days matters for the three variables that cannot be negative (wind speed, radiation, reference ET); for temperatures in kelvin a negative value would mean a units error. zero cell-days counts land cells with a value of exactly zero.

def per_var(v, col):
    return daily.loc[daily["variable"] == v, col]


qc = pd.DataFrame([{
    "variable": v,
    "units": UNITS[v],
    "days expected": len(expected),
    "days missing": len(expected - set(lists[v]["date"])),
    "min/max mismatches": mismatch[v],
    "valid cells (min-max)": f"{per_var(v, 'valid').min()}-{per_var(v, 'valid').max()}",
    "days land mask differs": int((~per_var(v, "same_land")).sum()),
    "negative cell-days": int(per_var(v, "negative").sum()),
    "zero cell-days": int(per_var(v, "zero").sum()),
    "min": per_var(v, "min").min(),
    "max": per_var(v, "max").max(),
} for v in VARS])
qc.to_csv(OUT_DIR / "qc.csv", index=False)
flags.to_csv(OUT_DIR / "qc_flags.csv", index=False)
print(qc.to_string(index=False, float_format="{:.6g}".format))
variable     units  days expected  days missing  min/max mismatches valid cells (min-max)  days land mask differs  negative cell-days  zero cell-days      min         max
    tmax         K          17167             0                   0             1113-1113                       0                   0               0  289.555     312.551
    tmin         K          17167             0                   0             1113-1113                       0                   0               0  284.188     302.987
    tdew         K          17167             0                   0             1113-1113                       0                   0               0  273.972     299.525
    ws10     m s-1          17167             0                   0             1113-1113                       0                   0              51        0     19.5824
    srad J m-2 d-1          17167             0                   0             1113-1113                       0                   0               1        0 3.04365e+07
     et0    mm d-1          17167             0                   0             1113-1113                       0                   0               0 0.383761      8.2752

Look before moving on. The table keeps one minimum and one maximum per variable for the whole record. The daily values behind them, which the pass stored in daily, show whether those extremes are single odd days or part of the normal spread. The figure draws, per variable and in its own units, how the daily land minimum and daily land maximum are distributed. Temperatures in kelvin should form a band far above 0 K (values between about 0 and 40 would be degrees Celsius), and the lower edge for wind, radiation and reference ET should be at or above zero. A lone bar far from the rest is a day worth finding in daily before going on.

fig, axes = plt.subplots(2, 3, figsize=(11, 5), constrained_layout=True)
for ax, v in zip(axes.flat, VARS):
    d = daily[daily["variable"] == v]
    edges = np.histogram_bin_edges(np.r_[d["min"], d["max"]], bins=40)
    ax.hist(d["min"], bins=edges, alpha=0.6, label="daily land minimum")
    ax.hist(d["max"], bins=edges, alpha=0.6, label="daily land maximum")
    ax.set_title(v, fontsize=10)
    ax.set_xlabel(UNITS[v], fontsize=9)
    ax.tick_params(labelsize=7)
for ax in axes[:, 0]:
    ax.set_ylabel("days", fontsize=9)
axes[0, 0].legend(fontsize=7, frameon=False)
plt.show()
for v in VARS:
    d = daily[daily["variable"] == v]
    print(f"{v}: daily land minimum {d['min'].min():.4g} to {d['min'].max():.4g}, "
          f"daily land maximum {d['max'].min():.4g} to {d['max'].max():.4g} {UNITS[v]}")

tmax: daily land minimum 289.6 to 300.6, daily land maximum 301.8 to 312.6 K
tmin: daily land minimum 284.2 to 292, daily land maximum 298.5 to 303 K
tdew: daily land minimum 274 to 292.6, daily land maximum 292.2 to 299.5 K
ws10: daily land minimum 0 to 1.412, daily land maximum 2.469 to 19.58 m s-1
srad: daily land minimum 0 to 2.404e+07, daily land maximum 1.174e+07 to 3.044e+07 J m-2 d-1
et0: daily land minimum 0.3838 to 4.642, daily land maximum 3.418 to 8.275 mm d-1

The cross-variable cases, by check and by year, and the largest of them:

if flags.empty:
    print("no cross-variable cases")
else:
    by_year = flags.assign(year=pd.to_datetime(flags["date"]).dt.year)
    print(by_year.groupby(["check", "year"]).agg(cell_days=("excess_K", "size"), days=("date", "nunique"),
                                                 largest_K=("excess_K", "max")).to_string())
    print("\nlargest cases:")
    print(flags.nlargest(5, "excess_K").to_string(index=False))
                      cell_days  days  largest_K
check           year                            
tdew above tmax 1981          4     2   0.873291
                1991          2     1   0.200775
                1993          1     1   0.093414
                1995          4     1   0.442932
                2006          2     1   0.931580
                2007          7     3   1.566467
                2012          1     1   0.027313
                2013          8     2   1.820099
                2014          1     1   0.471283
                2016          5     2   0.724396
                2022          8     2   1.886292
tmin above tmax 1979         17     8   0.322327
                1981        128    19   1.292694
                1982         10     3   0.098450
                1983         18     3   0.344971
                1984          6     4   0.258545
                1985          7     3   0.275787
                1986         72    17   1.000153
                1987         10     4   0.461823
                1988         10     3   0.104950
                1989         36     8   0.521088
                1990         21     4   0.579590
                1991         14     4   0.549316
                1992         22     5   0.442841
                1993          6     3   0.153259
                1994          2     2   0.170532
                1995         21     5   0.986298
                1996          9     3   0.388123
                1997          6     2   0.159637
                1998         51    12   0.650696
                1999         45     3   0.517792
                2000         19     5   0.282104
                2001         40     5   1.341827
                2002          5     1   0.409027
                2003          5     5   0.466034
                2004         22     6   0.499756
                2005          1     1   0.059692
                2006         47     7   0.523987
                2007         86    11   0.577209
                2008          2     1   0.030060
                2009          6     4   0.253906
                2010        183    30   0.826294
                2011         18     4   0.369659
                2012         22     6   0.417877
                2013        194    29   0.959686
                2014        125    12   1.488770
                2015         11     3   0.155762
                2016        157    15   0.883423
                2017         70    12   0.877075
                2018         28     8   1.111298
                2019          6     2   0.254578
                2020         98    16   1.120575
                2021         29     8   0.270813
                2022        155    20   0.980042
                2023         76    15   0.636627
                2024         59    16   0.511536
                2025         17     2   0.399200

largest cases:
          check       date   lat   lon  excess_K
tdew above tmax 2022-06-30  -9.6 124.3  1.886292
tdew above tmax 2013-06-21  -9.6 124.3  1.820099
tdew above tmax 2007-06-26  -9.6 124.3  1.566467
tmin above tmax 2014-07-14  -9.9 119.7  1.488770
tmin above tmax 2001-06-21 -10.2 120.0  1.341827

Look before moving on. Where do the cases fall? The cell counts them per cell from the flags table the pass already built, nothing is read again, and draws one map per check, each on its own colour scale. Land cells without a case show the lowest colour and the sea stays empty. Cases on most of the land, or in a block with a straight edge, would point to a processing error (swapped variables, a misplaced cut-out) rather than to the data. The printed line gives the number of land cells with at least one case; the paragraph after the figures reads it for the full record.

for check in ["tmin above tmax", "tdew above tmax"]:
    c = np.where(land, 0.0, np.nan)  # 0 on land, null over the sea
    for (la, lo), n in flags[flags["check"] == check].groupby(["lat", "lon"]).size().items():
        c[np.flatnonzero(lat == la)[0], np.flatnonzero(lon == lo)[0]] = n
    preview.array_maps([c], [f"{check}: cell-days per cell, {YEARS[0]}-{YEARS[-1]}"], "cell-days",
                       extent=preview.region_extent(), panel_width=4.5, digits=1)
    print(f"{check}: {int((c > 0).sum())} of {int(land.sum())} land cells have at least one case")

tmin above tmax: cell-days per cell, 1979-2025: 2,048 cells, 935 null; min 0.0, mean 1.8, max 118.0 cell-days
tmin above tmax: 164 of 1113 land cells have at least one case

tdew above tmax: cell-days per cell, 1979-2025: 2,048 cells, 935 null; min 0.0, mean 0.0, max 14.0 cell-days
tdew above tmax: 15 of 1113 land cells have at least one case

What the full record shows, when tested (1979-2025, 19,106,871 land cell-days):

  • Tmin above Tmax on 1,992 cell-days (0.010%), on 359 days in 46 of the 47 years, in 164 of the 1,113 land cells. 1,800 of them fall in May to August. The median excess is 0.14 K and the largest 1.49 K (9.9 S, 119.7 E, 14 July 2014). If you ran the teaching years, your table shows 11 cases in 2015, the ones Chapter 2 found, and 157 in 2016.
  • Dew point above Tmax on 43 cell-days, on 17 days in 15 cells, largest 1.89 K (9.6 S, 124.3 E, 30 June 2022). The checkpoint prints this share as 0.000% because it rounds to three decimals; it is about two in a million.
  • Exact zeros: wind speed is exactly 0 m s-1 on 51 cell-days in 12 cells. Solar radiation is 0 on one cell-day, 21 June 2013 at 9.8 S, 124.6 E; that day the eight cells around it received 0.16 to 1.63 MJ m-2, against 14 to 17 MJ m-2 in the same cell on 15-20 June; the next three days were also low (5.1, 5.8 and 12.9 MJ m-2).

All of these are in the source files: the largest cases were read again from the original yearly archive files, and the 2015-2016 cases are the same in the CDS downloads. The AgERA5 user guide documents a related case: in version 2.0 the bias corrections are applied to Tmin, Tmean and Tmax independently, so Tmean can exceed Tmax (PUGS, section 5.3). It does not mention Tmin or dew point above Tmax. They are kept as they are, not corrected. Chapter 4 decides how its evapotranspiration calculation treats them, since it uses Tmin, Tmax, dew point, wind and radiation together.

AgERA5 version 2.0 also has a documented artefact in wind speed: a sinusoidal pattern at some high-elevation points (PUGS, known issues). A check for it needs elevation, which arrives in Chapter 4, so it is left there.

9. One look at the record

A chart of the daily land mean of each variable, from the daily table of section 8, is a quick way to see a broken year, a unit jump or a gap that the checks did not anticipate. It is a sanity check, not an analysis.

Look before moving on. A healthy record shows the same seasonal cycle repeating each year in every panel, with no step at the start of a year. A whole year at a different level, a flat stretch, or a panel that looks like another variable would mean an import or a registration went wrong for that year, even if the checks above passed.

import matplotlib.pyplot as plt

fig, axes = plt.subplots(3, 2, figsize=(11, 7), sharex=True)
for ax, v in zip(axes.flat, VARS):
    d = daily[daily["variable"] == v]
    ax.plot(pd.to_datetime(d["date"]), d["mean"], lw=0.5)
    ax.set_title(f"{v} ({UNITS[v]})", fontsize=10)
fig.suptitle(f"Daily mean over {AOI_NAME.upper()} land cells, {YEARS[0]}-{YEARS[-1]}")
fig.tight_layout()
plt.show()

10. Checkpoint

These checks read from GRASS: the datasets and their maps in agera5, units and semantic labels on every map, and the search path of ch03.

Chapter 2 stopped when Tmin was more than 0.5 K above Tmax. Over more years single cases go higher (0.88 K in 2016 when tested), so the size of one case cannot tell a quirk of the data from swapped variables. The count can: swapped Tmin and Tmax, or Tmax in the wrong units, would be flagged on nearly every land cell-day. (Other unit errors are caught by the units check in section 4.) The checkpoint stops if more than 1% are, a limit chosen far from both, and prints the share it found.

def folder_stats(path):
    files = [f for f in Path(path).rglob("*") if f.is_file()] if Path(path).exists() else []
    return len(files), sum(f.stat().st_size for f in files) / 1e6


t0 = time.time()
assert gs.gisenv()["MAPSET"] == CHECKS and RAW in search_path()
for v in VARS:
    df = listing(v)
    assert expected <= set(df["date"]), f"{v}: days missing"
    assert df["date"].is_unique, f"{v}: a day registered twice"
    info = gs.parse_command("t.info", input=f"{v}@{RAW}", flags="g")
    assert info["start_time"].strip("'")[:10] <= f"{YEARS[0]}-01-01" and info["end_time"].strip("'")[:10] >= f"{YEARS[-1]}-12-31"
    for y in YEARS:
        for n in map_names(v, y):
            i = Info(n, RAW)
            assert (i.units, i.semantic_label) == (UNITS[v], v), f"{n}: units or semantic label missing"
assert sum(mismatch.values()) == 0 and sample_bad == 0, "GRASS maps differ from the prepared files"
assert (qc["days land mask differs"] == 0).all(), "the land mask changes"
assert (qc.loc[qc["variable"].isin(["ws10", "srad", "et0"]), "negative cell-days"] == 0).all(), "negative wind, radiation or ET"
cell_days = int(land.sum()) * len(expected)
for check in ["tmin above tmax", "tdew above tmax"]:
    n = int((flags["check"] == check).sum())
    print(f"{check}: {n:,} of {cell_days:,} land cell-days ({n / cell_days:.3%}), limit 1%")
    assert n / cell_days < 0.01, f"{check}: swapped variables or wrong units?"
assert (OUT_DIR / "qc.csv").exists()

n_files, mb_grass = folder_stats(PROJECT / RAW)
used = [p for v, y in need for p in (DL_DIR / f"agera5_{v}_{y}_{AOI_NAME}.zip", DL_DIR / f"{v}_{y}_{AOI_NAME}")]
mb_dl = sum(folder_stats(p)[1] if p.is_dir() else p.stat().st_size / 1e6 for p in used if p.exists())
print("All checks passed." + ("" if RUN_FULL else " This was the teaching run: Chapters 4 and 5 need run_full: true."))
print(f"Mapset {RAW}: {n_files:,} files, {mb_grass:.0f} MB | prepared files: {folder_stats(STAGED)[1]:.0f} MB | "
      f"downloads used by this run: {mb_dl:.0f} MB")
print(f"Checkpoint {time.time() - t0:.0f} s | chapter run time: {time.time() - CHAPTER_START:.0f} s")
tmin above tmax: 1,992 of 19,106,871 land cell-days (0.010%), limit 1%
tdew above tmax: 43 of 19,106,871 land cell-days (0.000%), limit 1%
All checks passed.
Mapset agera5: 1,339,030 files, 771 MB | prepared files: 392 MB | downloads used by this run: 0 MB
Checkpoint 326 s | chapter run time: 3626 s

Summary

What now exists:

  • Mapset agera5: daily maps <variable>_YYYYMMDD for tmax, tmin, tdew, ws10, srad and et0, each with units and a semantic label, registered in six datasets of the same names.
  • Mapset ch03: its region, its own (empty) temporal database, and a search path that includes agera5.
  • On disk: one prepared NetCDF per variable-year in paths.staged; CDS zips and their daily files in paths.downloads/agera5 if you downloaded; qc.csv, qc_flags.csv and the registration files register_<variable>.txt in paths.outputs/ch03.

What you can now do: estimate a long job from a measured sample, import years of daily data in a form that scales, register it safely, read it from another mapset, and check it.

Before Chapter 4, if you ran the teaching years:

  1. Set run_full: true in config.yml.
  2. Restart the kernel.
  3. Run the whole chapter again. Finished years are skipped; time and disk are in At a glance.

Chapter 4 computes ASCE reference evapotranspiration from tmax, tmin, tdew, ws10 and srad, and compares it with et0.

Troubleshooting

Symptom Cause Fix
AssertionError: no daily files for ... in section 3 the downloads were not unzipped run section 2 first; it unzips every zip it uses
ValueError: ... inside OneDrive or ... not an absolute path paths.staged, downloads or outputs in config.yml set them to absolute folders outside OneDrive
RuntimeError: ... dates are not every day of ... a prepared file or download is incomplete delete that file in paths.staged (or the zip) and re-run sections 2 and 4
Section 5 reports band-named maps left over a run stopped between import and rename re-run the three cells of section 5
t.rast.list ... no permission to access mapset the mapset is not on the search path g.mapsets operation=add mapset=agera5 (section 7)
GrassError: Map <...> not found in current mapset from Info setting units on a map outside the mapset the kernel started in (section 7) set units before switching mapsets, or start the kernel in that mapset
Cells above section 7 behave oddly when re-run the kernel is in ch03 after section 7 restart the kernel and run from Setup
You interrupted a cell that runs a queue the GRASS processes it started may still be running restart the kernel and re-run only when no r.in.gdal or g.rename processes remain (Task Manager), so two processes never write the same maps
A map or dataset was replaced without warning GRASS_OVERWRITE=1 from grass.jupyter keep the GRASS_OVERWRITE = "0" line in the setup cell
Too many open files from a t.rast.* module every input map held open set file_limit: when tested on Windows the default failed at the 52nd map, and Chapter 2 uses 40 (section 6)
A CDS request fails part-way queue or network problem re-run section 2; finished years are skipped and the unfinished download starts again

References