Skip to main content

Chapter 5: The Evaporative Demand Drought Index

Tutorial series: Climate Analysis with GRASS and Python

Chapter 5: The Evaporative Demand Drought Index

TipAt a glance
  • You will build: monthly EDDI at 1, 3, 6 and 12-month timescales for every month of 1979-2025 that has a full window, ranked against the 1991-2020 baseline, as four GRASS time series; drought and wet categories; and a check against an independent Python implementation.
  • Record: EDDI needs the climatology, so this chapter always uses the whole etrs record of Chapter 4.
  • You need: Chapter 4 run with run_full: true (dataset etrs in mapset ch04, 1979-2025). The check in section 7 also uses the output of the eddi repository if it is on your disk; without it that one cell is skipped.
  • Time and disk: when tested on Windows 11 with 8 of 80 logical CPUs in use, 402 s in all, the preview figures included: monthly totals 100 s, writing and registering 2,238 EDDI maps 216 s, the checkpoint 54 s. Mapset ch05 then holds 36,780 files, 18 MB. A second run skips finished work.
NoteLearning objectives

After this chapter you can:

  1. Aggregate a daily time series to monthly totals and build multi-month windows.
  2. Rank each window against the same calendar window of a baseline, in r.mapcalc and through the numpy bridge, and show the two agree.
  3. Turn ranks into probabilities and standardized values, and say what each step assumes.
  4. Map drought categories and follow one event through four timescales.
  5. Cross-check against an independent implementation and say what agreement does and does not prove.

Setup

The kernel starts in a new mapset, ch05, and reads etrs from ch04 through the search path. As in Chapter 4:

  • GRASS_OVERWRITE=0 undoes the overwrite-everything default of grass.jupyter;
  • g.mapsets operation=add puts ch04 on the search path;
  • g.gisenv set=NPROCS=1 gives each GRASS tool one thread unless a call asks for more; N_PARALLEL is how many GRASS processes run side by side.

pg.start also sets the region to the area at 0.1 degree; nothing here changes it. BASELINE comes from config.yml (baseline: [1991, 2020]), the 30-year reference period the WMO asks countries to adopt (WMO). NOAA’s operational EDDI ranks against its whole record instead; section 7 shows what that choice changes.

import datetime as dt
import json
import os
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 eddi, tgis
from pgca import session as pg

cfg = pg.load_config(ROOT / "config.yml")
SRC = "ch04"    # mapset holding etrs (Chapter 4)
HERE = "ch05"   # this chapter's maps
session = pg.start(cfg, mapset=HERE)
os.environ["GRASS_OVERWRITE"] = "0"

import grass.jupyter as gj
import grass.script as gs
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
from grass.pygrass.modules import Module, ParallelModuleQueue
from grass.pygrass.raster import numpy2raster, raster2numpy
from grass.pygrass.raster.abstract import Info

if SRC not in gs.parse_command("g.mapsets", flags="p", format="json")["mapsets"]:
    gs.run_command("g.mapsets", operation="add", mapset=SRC)
gs.run_command("g.gisenv", set="NPROCS=1")

AOI_NAME = cfg["active_aoi"]
PROJECT = Path(cfg["paths"]["grassdata"]) / cfg["grass"]["project"]
BASELINE = list(range(cfg["baseline"][0], cfg["baseline"][1] + 1))
TIMESCALES = [1, 3, 6, 12]
N_PARALLEL = min(8, os.cpu_count() or 1)
OUT_DIR = pg.check_data_path(cfg["paths"]["outputs"]) / "ch05"
OUT_DIR.mkdir(parents=True, exist_ok=True)

src_info = tgis.info(f"etrs@{SRC}")
assert src_info["start_time"][:10] <= f"{BASELINE[0]}-01-01" and src_info["end_time"][:10] >= f"{BASELINE[-1] + 1}-01-01", \
    "etrs does not cover the baseline: run Chapter 4 with run_full: true"
reg = gs.region()
EXTENT = [reg["w"], reg["e"], reg["s"], reg["n"]]  # for matplotlib maps
LAT = reg["n"] - reg["nsres"] * (np.arange(reg["rows"]) + 0.5)  # cell centres, used in section 7
LON = reg["w"] + reg["ewres"] * (np.arange(reg["cols"]) + 0.5)
print("Mapset:", gs.gisenv()["MAPSET"], "| etrs:", src_info["number_of_maps"], "days,",
      src_info["start_time"][:10], "to", src_info["end_time"][:10])
print("Baseline:", BASELINE[0], "to", BASELINE[-1], f"({len(BASELINE)} years) | timescales (months):", TIMESCALES)
Mapset: ch05 | etrs: 17167 days, 1979-01-01 to 2026-01-01
Baseline: 1991 to 2020 (30 years) | timescales (months): [1, 3, 6, 12]

1. What EDDI measures

The Evaporative Demand Drought Index asks one question per place and month: how unusual has the atmosphere’s demand for water been over the last months? The EDDI papers call that demand E0; in this series it is the ETrs of Chapter 4, ASCE’s tall reference crop, as in NOAA’s EDDI. The recipe, in the words of the EDDI User Guide (p15): calculate daily reference evapotranspiration “and aggregate it over the selected time window”, then place that total in the place’s own climatology “using rank-based non-parametric probabilities”. Positive EDDI means more demand than usual, which worsens drought where water is short; negative means less. EDDI does not measure conditions on the ground (rain, soil moisture or crops); it describes the atmosphere’s side of drought.

Its use is as an early signal: Hobbins et al. (2016) found it “in some hydroclimates offering early warning relative to current operational drought indices”, chiefly the US Drought Monitor, because hot, dry, sunny and windy weeks raise demand before drought impacts show. The index is multi-scalar: the same recipe at different window lengths (timescales) answers different questions, from a dry month to a dry year.

How this chapter’s EDDI differs from NOAA’s operational product (NOAA PSL EDDI):

NOAA PSL EDDI This chapter
Input NLDAS-2, about 12 km, United States AgERA5, 0.1 degree, NTT
Reference crop “0.5-m tall reference crop” tall alfalfa, 0.50 m (ETrs, Chapter 4)
Baseline the whole record 1991-2020
Timescales 1-12 weeks and 1-12 months; an “EDDI month” is 30 days (User Guide, p22) 1, 3, 6 and 12 calendar months, at month ends
What is ranked the total over the window the mean per day over the window (section 3)

The method (Hobbins et al. 2016, section 3a, pp. 1748-1749):

  1. Aggregate E0 over the window. Their example: a 2-month EDDI on 31 January sums 1 December to 31 January.
  2. Rank the window among the same window in every year of the baseline, i=1i = 1 for the largest, and turn the rank into a probability with the Tukey plotting position, a rule that converts the rank of one value among nn into an estimate of how often such a value is exceeded: P=i−0.33n+0.33P = \frac{i - 0.33}{n + 0.33} nn is the number of years ranked: the baseline length for a year inside the baseline, “augmented by 1” (p. 1749) for a year outside it, which is ranked among the baseline years plus itself and so can be a new extreme.
  3. Standardize: turn PP into a value on the standard normal scale with a rational approximation of the inverse normal (their eq 4, after Vicente-Serrano et al. 2010): EDDI=W−C0+C1W+C2W21+d1W+d2W2+d3W3,W=−2ln⁡PEDDI = W - \frac{C_0 + C_1 W + C_2 W^2}{1 + d_1 W + d_2 W^2 + d_3 W^3}, \quad W = \sqrt{-2 \ln P} with C0C_0 = 2.515517, C1C_1 = 0.802853, C2C_2 = 0.010328, d1d_1 = 1.432788, d2d_2 = 0.189269, d3d_3 = 0.001308. For P>0.5P > 0.5, use 1−P1 - P and reverse the sign.

EDDI is 0 at the baseline median and positive when demand was higher than usual.

Three words, used strictly from here on. PP above is a probability of exceedance: small when demand was high. This chapter mostly uses its complement, the probability 1−P1 - P: the share of baseline years with less demand, high when demand was high. The percentile is that probability times 100; the drought categories (section 6) are percentile ranges. pgca.eddi.tukey_probability() returns the probability 1−P1 - P, computed from the paper’s ii exactly; pgca.eddi.inverse_normal() then gives EDDI.

What each step assumes. Ranking assumes the baseline years are comparable: no trend strong enough to make early years a different climate. The Tukey position is one of several rank-to-probability rules (the Weibull rule i/(n+1)i / (n + 1) is another); Hobbins et al. use it because it suits comparisons between standardized drought indices. The inverse-normal step is an approximation; within 0.001 < p < 0.999 it stays within 4.5e-4 of the exact normal quantile (tests/test_eddi.py).

The range EDDI can take is set by nn, since the most extreme rank gives the most extreme probability. The cell prints it for this chapter’s two cases and for the paper’s 36-year climatology, which the paper gives as about +-2.09.

for n in (len(BASELINE), len(BASELINE) + 1, 36):
    hi = float(eddi.inverse_normal(eddi.tukey_probability(n, n)))
    lo = float(eddi.inverse_normal(eddi.tukey_probability(1, n)))
    print(f"n = {n}: EDDI from {lo:+.3f} to {hi:+.3f}")
n = 30: EDDI from -2.019 to +2.013
n = 31: EDDI from -2.033 to +2.026
n = 36: EDDI from -2.094 to +2.087

2. Monthly totals

t.rast.aggregate sums the daily maps of each calendar month into one map (method=sum; the dataset’s semantic type sum from Chapter 4 does not choose this for you). It runs one r.series per month, nprocs of them at a time. suffix="gran" names the outputs by their month (etrs_month_1979_01). file_limit=40 would make r.series read its inputs without keeping them all open in months of more than 40 maps; a month has at most 31, under the roughly 50 that failed in Chapter 2, so it never triggers here.

r.series skips days with no value, so the sea stays empty, but so would a land cell with a missing day, which would then get a short total. The check after this cell rules that out for one month. Two more details: t.rast.aggregate copies the daily dataset’s title and description, so the cell replaces them, and it sets no units, so the cell adds mm. The description records the source dataset’s period; if Chapter 4 is re-run for a different period, the cell re-aggregates.

strds_here() lists the datasets in this mapset; tgis.n_maps() reads how many maps a dataset holds (0 if an interrupted registration left the count empty).

Slow cell: when tested, 100 s for 564 months. It is skipped when etrs_month is complete and up to date.

def strds_here():
    return {s.split("@")[0] for s in gs.read_command("t.list", type="strds", where=f"mapset = '{HERE}'").split()}


n_months = (int(src_info["end_time"][:4]) - int(src_info["start_time"][:4])) * 12
month_desc = f"Sum of daily etrs@{SRC} per calendar month, {AOI_NAME}, {src_info['start_time'][:10]} to {src_info['end_time'][:10]}"
t0 = time.time()
current = "etrs_month" in strds_here() and tgis.n_maps("etrs_month") == n_months \
    and tgis.description("etrs_month") == month_desc
if not current:
    Module("t.rast.aggregate", input=f"etrs@{SRC}", output="etrs_month", basename="etrs_month",
           granularity="1 months", method="sum", suffix="gran", nprocs=N_PARALLEL, file_limit=40, overwrite=True)
    Module("t.support", input="etrs_month", title="Monthly ETrs totals", description=month_desc)
rows = json.loads(gs.read_command("t.rast.list", input="etrs_month", columns="name,start_time,end_time", format="json"))["data"]
months = pd.DataFrame(rows)
months["start"] = pd.to_datetime(months["start_time"])
months["days"] = (pd.to_datetime(months["end_time"]) - months["start"]).dt.days
months["year"], months["month"] = months["start"].dt.year, months["start"].dt.month
for name in months["name"]:
    if Info(name, HERE).units != "mm":
        Info(name, HERE).units = "mm"
land = np.isfinite(raster2numpy(months["name"].iloc[0]))  # land cells, used in every later section
print(f"{len(months)} monthly maps ({time.time() - t0:.0f} s); first {months['name'].iloc[0]}, last {months['name'].iloc[-1]}; "
      f"{land.sum()} land cells")
564 monthly maps (100 s); first etrs_month_1979_01, last etrs_month_2025_12; 1113 land cells

A check of one month: December 2015 summed from its 31 daily maps in numpy must equal the monthly map, and every land cell must have all 31 days.

dec = months[(months["year"] == 2015) & (months["month"] == 12)].iloc[0]
daily = sum(raster2numpy(f"etrs_201512{d:02d}@{SRC}").astype(float) for d in range(1, 32))
monthly = raster2numpy(dec["name"])
assert np.array_equal(np.isfinite(daily), land), "a land cell has a missing day"
print(f"{dec['name']}: max |monthly - sum of days| = {np.nanmax(np.abs(monthly - daily)):.1e} mm; "
      f"land mean {np.nanmean(monthly):.1f} mm in {dec['days']} days")
etrs_month_2015_12: max |monthly - sum of days| = 0.0e+00 mm; land mean 162.0 mm in 31 days

Look before moving on. The check covered one month by its numbers; now look at two monthly totals from different seasons of 2015, read back from GRASS on one colour scale in mm. A correct result has the sea empty, a positive total on every land cell, and values that change gradually from cell to cell. A land cell left empty, or a straight-edged patch much lower than its neighbours, would mean missing days in that month, and the error would carry into every window built from it in section 3. The two months differ by season and also by length (the titles give the days), so compare their totals with that in mind.

pgca.preview is the series’ small drawing helper: preview.maps() reads GRASS maps in the current region, draws them side by side, and prints one summary line per map.

from pgca import preview

pv_months = months[(months["year"] == 2015) & months["month"].isin([6, 12])]
preview.maps(list(pv_months["name"]), [f"{nm} ({d} days)" for nm, d in zip(pv_months["name"], pv_months["days"])], "mm",
             cmap="YlOrRd", suptitle="Monthly ETrs totals, 2015");

etrs_month_2015_06 (30 days): 2,048 cells, 935 null; min 89.33, mean 158.56, max 234.44 mm
etrs_month_2015_12 (31 days): 2,048 cells, 935 null; min 115.90, mean 162.03, max 221.34 mm

3. Windows

Two words: the timescale k is a window length in months; the window ending in a month is that month and the k - 1 before it. EDDI ranks each window against the same window in other years: the 3 months to December 2015 against the 3 months to December of every baseline year.

This chapter ranks the mean per day over the window rather than the total the User Guide describes. For windows of equal length the two give the same order, but a 1-month February window is 29 days long in leap years, so its total would rank higher for the extra day alone; dividing by the number of days removes that. (NOAA avoids the problem differently, with 30-day “months”.)

One window built in r.mapcalc first, so you can see it is just a sum divided by its days:

names = dict(zip(zip(months["year"], months["month"]), months["name"]))
ndays_of = dict(zip(zip(months["year"], months["month"]), months["days"]))
oct_dec = [(2015, 10), (2015, 11), (2015, 12)]
expr = " + ".join(names[m] for m in oct_dec)
Module("r.mapcalc", expression=f"w03_2015_12 = float(({expr}) / {sum(ndays_of[m] for m in oct_dec)})", overwrite=True)
Info("w03_2015_12", HERE).units = "mm d-1"
print("w03_2015_12 =", f"({expr}) / {sum(ndays_of[m] for m in oct_dec)}")
w03_2015_12 = (etrs_month_2015_10 + etrs_month_2015_11 + etrs_month_2015_12) / 92

All windows of all timescales in numpy, through the numpy bridge: pygrass’s raster2numpy() and numpy2raster(), which move maps between GRASS and numpy arrays in the current region. The 564 monthly maps are read once into one array, and pgca.eddi.window_means() uses running sums, so each window costs two subtractions. One r.mapcalc per window would also work, but when tested (ledger C92) the 1,674 windows of the 3, 6 and 12-month timescales took 322 s that way.

means[k] (one array per timescale) is used by every later section. The cell prints the memory it takes: it grows with the area, and section 5 would need to work one timescale at a time for a much larger area.

t0 = time.time()
totals = np.stack([raster2numpy(n) for n in months["name"]]).astype(float)
ndays = months["days"].to_numpy()
means = {k: eddi.window_means(totals, ndays, k) for k in TIMESCALES}
i_dec15 = int(np.flatnonzero((months["year"] == 2015) & (months["month"] == 12))[0])
check = np.nanmax(np.abs(raster2numpy("w03_2015_12") - means[3][i_dec15]))
print(f"read {len(months)} maps and built {len(TIMESCALES)} timescales in {time.time() - t0:.1f} s; "
      f"{(totals.nbytes * (1 + len(TIMESCALES))) / 1e6:.0f} MB in memory; r.mapcalc window vs numpy, Dec 2015: {check:.1e} mm/day")
read 564 maps and built 4 timescales in 2.7 s; 46 MB in memory; r.mapcalc window vs numpy, Dec 2015: 2.4e-07 mm/day

Look before moving on. totals now holds every monthly total in memory, so the whole record can be drawn without reading a map again: the land mean of each month’s total, in mm. Expect a seasonal cycle that repeats every year, with no month at zero and no gap. A missing month or a sudden step would point to a month aggregated from an incomplete set of days, and every window that contains it would inherit the error. February sits lower partly because it is shorter; the windows remove that by dividing by the days.

pv_land_total = np.nanmean(totals[:, land], axis=1)
preview.series(months["start"], {"land mean monthly total": pv_land_total}, "mm",
               title="Monthly ETrs totals, land mean", xlabel="month");

land mean monthly total: 564 values, 0 null; min 124.63, mean 160.72, max 196.97 mm

Look before moving on. The four timescales for the same land mean, 2013-2017, as the mean per day over the window ending in each month (mm/day). The 1-month line follows each month; the longer the window, the smoother and later its line should be, and the 12-month line should be nearly flat, since each of its values averages a whole year. A long window that swings more than a short one, or a jump in one line that the others do not echo, would mean the running sums are misaligned with the months.

pv_sel = ((months["year"] >= 2013) & (months["year"] <= 2017)).to_numpy()
preview.series(months["start"][pv_sel], {f"{k} month": np.nanmean(means[k][pv_sel][:, land], axis=1) for k in TIMESCALES},
               "mm/day", title="Mean ETrs over the window ending in each month, land mean", xlabel="month in which the window ends");

1 month: 60 values, 0 null; min 4.35, mean 5.28, max 6.32 mm/day
3 month: 60 values, 0 null; min 4.70, mean 5.29, max 6.17 mm/day
6 month: 60 values, 0 null; min 4.74, mean 5.30, max 5.80 mm/day
12 month: 60 values, 0 null; min 5.15, mean 5.31, max 5.47 mm/day

4. One month, step by step

The 3 months to December 2015, in GRASS. The cell is written for any timescale K, end month M and year Y inside the baseline (an assert says so): a year outside the baseline needs the n + 1 rule, which section 5 handles.

  1. Baseline windows: one map per baseline year, w03_1991_12 and so on, each a mean per day.
K, M, Y = 3, 12, 2015
assert Y in BASELINE, "this step-by-step cell is written for a year inside the baseline"
pos = {key: i for i, key in enumerate(zip(months["year"], months["month"]))}


def window_parts(y):
    i = pos[(y, M)]
    return [tuple(months[["year", "month"]].iloc[j]) for j in range(i - K + 1, i + 1)]


win = {b: f"w{K:02d}_{b}_{M:02d}" for b in BASELINE}
queue = ParallelModuleQueue(nprocs=N_PARALLEL)
for b in BASELINE:
    parts = window_parts(b)
    expr = " + ".join(names[p] for p in parts)
    queue.put(Module("r.mapcalc", expression=f"{win[b]} = float(({expr}) / {sum(ndays_of[p] for p in parts)})",
                     nprocs=1, overwrite=True, run_=False))
queue.wait()
print(f"{len(win)} window maps, for example {win[BASELINE[0]]} = mean of {window_parts(BASELINE[0])}")
30 window maps, for example w03_1991_12 = mean of [(1991, 10), (1991, 11), (1991, 12)]

Look before moving on. The window maps just written, read back from GRASS and averaged over land: one value per baseline year, with the value of the year being ranked drawn as a flat line. Expect values that vary a little from year to year around a steady level, with every year present. A gap or a year far from the rest would mean a missing or wrongly built map, and it would shift every rank computed next. The position of the flat line among the dots, printed under the plot, gives a first idea of the ranks in the next step; ranks there are per cell, so they spread around it.

pv_base = np.array([np.nanmean(raster2numpy(win[b])[land]) for b in BASELINE])
pv_cur = pv_base[BASELINE.index(Y)]
fig, ax = plt.subplots(figsize=(9, 3), constrained_layout=True)
ax.plot(BASELINE, pv_base, "o-", lw=1, ms=3, label="baseline years")
ax.axhline(pv_cur, color="C3", lw=1, label=str(Y))
ax.set(xlabel="year", ylabel="mm/day", title=f"{K}-month windows ending in month {M}, land mean")
ax.legend(fontsize=8, frameon=False)
ax.grid(alpha=0.3)
plt.show()
print(preview.format_summary("baseline windows", preview.summary(pv_base), "mm/day").replace(" cells", " values"))
print(f"{Y}: {pv_cur:.2f} mm/day, {int(np.sum(pv_base < pv_cur)) + 1} of {len(BASELINE)} counted from the lowest")

baseline windows: 30 values, 0 null; min 5.01, mean 5.54, max 5.91 mm/day
2015: 5.82 mm/day, 27 of 30 counted from the lowest
  1. Rank, probability, EDDI. The rank of 2015 among the baseline is an r.mapcalc sum of comparisons: (w_1991 < w_2015) + (w_1992 < w_2015) + ... counts the years with a lower value, and adding 1 gives the rank, smallest = 1. A tie would count half; the map is compared with itself once, which is why - 1 appears in the tie term. The probability then converts to the paper’s i=n+1−ranki = n + 1 - \text{rank} (section 1), and EDDI comes from the inverse-normal formula, written once inside eval() so its intermediate values are not stored as maps.
cur = win[Y]
n = len(BASELINE)
below = " + ".join(f"({win[b]} < {cur})" for b in BASELINE)
ties = " + ".join(f"({win[b]} == {cur})" for b in BASELINE)
tag = f"{K:02d}_{Y}_{M:02d}"
Module("r.mapcalc", expression=f"rank{tag} = float(1 + {below} + (({ties}) - 1) / 2.0)", overwrite=True)
# probability 1 - P, with the paper's rank i = n + 1 - rank
Module("r.mapcalc", expression=f"prob{tag} = float(1 - (({n} + 1 - rank{tag}) - 0.33) / ({n} + 0.33))", overwrite=True)
Module("r.mapcalc", overwrite=True, expression=(
    f"eddi_step{tag} = eval(p = prob{tag}, q = if(p <= 0.5, p, 1 - p), w = sqrt(-2 * log(q)), "
    f"z = w - ({eddi.C0} + {eddi.C1} * w + {eddi.C2} * w * w) / (1 + {eddi.D1} * w + {eddi.D2} * w * w + {eddi.D3} * w * w * w), "
    f"float(if(p <= 0.5, -z, z)))"))
print("maps:", f"rank{tag}", f"prob{tag}", f"eddi_step{tag}")
maps: rank03_2015_12 prob03_2015_12 eddi_step03_2015_12

Look before moving on. The rank map and the EDDI map just written. Ranks must lie between 1 and the number of baseline years, as whole numbers or halves where years tie, and EDDI must stay inside the range section 1 printed for n = 30, with the sea empty on both. The two maps should show the same pattern, since EDDI only relabels the rank; on the diverging EDDI scale red is more demand than the baseline median and blue less. A rank outside that range, or an EDDI pattern that differs from the rank pattern, would mean an error in an expression; the numpy check in the next step tests the same thing cell by cell.

preview.maps([f"rank{tag}"], [f"rank of {Y} among {n} baseline years"], "rank (1 = lowest)", digits=1)
preview.maps([f"eddi_step{tag}"], [f"{K}-month EDDI, window ending {Y}-{M:02d}"], "EDDI (dimensionless)",
             cmap="RdBu_r", center=0);

rank of 2015 among 30 baseline years: 2,048 cells, 935 null; min 11.0, mean 25.2, max 30.0 rank (1 = lowest)

3-month EDDI, window ending 2015-12: 2,048 cells, 935 null; min -0.38, mean 1.04, max 2.01 EDDI (dimensionless)
  1. The same in numpy, and what it means. pgca.eddi.rank_in_baseline() and the two formulas give the numpy version, which must equal the GRASS maps. The last lines put the result in physical terms: the window’s mean ETrs against the baseline median, averaged over land, for the 1-month and the 3-month window.
base_np = np.stack([means[K][pos[(b, M)]] for b in BASELINE])  # (years, rows, cols), reused in section 7
rank_np, n_np = eddi.rank_in_baseline(means[K][pos[(Y, M)]], base_np, Y in BASELINE)
eddi_np = eddi.inverse_normal(eddi.tukey_probability(rank_np, n_np))
rank_g, eddi_g = raster2numpy(f"rank{tag}"), raster2numpy(f"eddi_step{tag}")
print(f"rank: GRASS vs numpy differ on {int(np.sum(rank_g[land] != rank_np[land]))} land cells; n = {n_np}; "
      f"ranks {np.nanmin(rank_g):.0f} to {np.nanmax(rank_g):.0f}; cells with a tie: {int(np.sum(rank_g[land] % 1 != 0))}")
print(f"EDDI: max |GRASS - numpy| {np.nanmax(np.abs(eddi_g - eddi_np)):.1e}; land mean {np.nanmean(eddi_g):+.2f}")
for k_ in (1, K):
    cur_mean = np.nanmean(means[k_][pos[(Y, M)]][land])
    med = np.nanmean(np.median(np.stack([means[k_][pos[(b, M)]] for b in BASELINE]), axis=0)[land])
    print(f"{k_}-month window to {Y}-{M:02d}: mean ETrs {cur_mean:.2f} mm/day vs baseline median {med:.2f} "
          f"({100 * (cur_mean / med - 1):+.1f}%), land mean")
rank: GRASS vs numpy differ on 0 land cells; n = 30; ranks 11 to 30; cells with a tie: 0
EDDI: max |GRASS - numpy| 4.7e-07; land mean +1.04
1-month window to 2015-12: mean ETrs 5.23 mm/day vs baseline median 5.03 (+4.0%), land mean
3-month window to 2015-12: mean ETrs 5.82 mm/day vs baseline median 5.56 (+4.7%), land mean

When tested, GRASS and numpy ranks agreed on every land cell and EDDI to 4.7e-07, with no ties. Ranks ran from 11th to 30th of 30 and the land mean EDDI was +1.04: most of the area was above its baseline median for these three months, some cells below it (the lowest EDDI on the map was -0.38).

In physical terms the 3-month window averaged 5.82 mm/day against a baseline median of 5.56 (+4.7%), and December alone 5.23 against 5.03 (+4.0%). Small percentages, high ranks: here evaporative demand varies little from year to year, so a few percent above the median is already unusual. That is why EDDI is read as a rank and not as a departure in millimetres.

5. Every month

The same steps for every month and timescale, in numpy, then written back to GRASS with numpy2raster as maps eddi_<k>m_YYYY_MM (for example eddi_03m_2015_12) and registered in four datasets, eddi_01m to eddi_12m. Each map is registered for the month its window ends in. Years inside the baseline are ranked among the 30 baseline values; years outside it (1979-1990, 2021-2025) among the 30 plus themselves, n = 31. A k-month timescale has no window for its first k - 1 months, so the datasets hold 564, 562, 559 and 553 maps.

compute() is pure numpy and returns the probability for every month. write() writes each map, then sets units last, so a re-run skips finished maps, as in Chapters 3 and 4. It also compares each dataset’s description, which records the baseline and the source period, with what this run would write: if baseline in config.yml or the etrs record changed, every map of that timescale is rewritten.

Slow cell: writing and registering 2,238 maps; when tested, 216 s.

def compute(k):
    out = {}
    year_of, month_of = months["year"].to_numpy(), months["month"].to_numpy()
    for m in range(1, 13):
        idx = [i for i in np.flatnonzero(month_of == m) if np.isfinite(means[k][i]).any()]
        base = means[k][[i for i in idx if year_of[i] in BASELINE]]
        for i in idx:
            r, n_years = eddi.rank_in_baseline(means[k][i], base, year_of[i] in BASELINE)
            out[(int(year_of[i]), m)] = eddi.tukey_probability(r, n_years)
    return out


def write(k, prob_k):
    prefix = f"eddi_{k:02d}m"
    desc = (f"EDDI from etrs@{SRC} ({src_info['start_time'][:10]} to {src_info['end_time'][:10]}), {k}-month window "
            f"ending in the month, baseline {BASELINE[0]}-{BASELINE[-1]}, {AOI_NAME}")
    finished = set()
    if prefix in strds_here() and tgis.description(prefix) == desc:
        existing = [s.split("@")[0] for s in gs.list_strings("raster", pattern=f"{prefix}_*", mapset=HERE)]
        finished = {s for s in existing if Info(s, HERE).units == "1"}
    elif prefix in strds_here():
        Module("t.support", input=prefix, description=desc)  # inputs changed: rewrite every map
    rows_ = []
    for (y, m), p in sorted(prob_k.items()):
        map_name = f"{prefix}_{y}_{m:02d}"
        if map_name not in finished:
            numpy2raster(eddi.inverse_normal(p).astype("float32"), "FCELL", map_name, overwrite=True)
            info_ = Info(map_name, HERE)
            info_.semantic_label = prefix
            info_.units = "1"  # dimensionless; set last to mark the map as finished
        rows_.append((map_name, dt.date(y, m, 1), dt.date(y + (m == 12), m % 12 + 1, 1)))
    return rows_, desc


t0 = time.time()
probs = {k: compute(k) for k in TIMESCALES}  # probability 1 - P per (year, month), used in sections 6-7
print(f"ranks and probabilities for all timescales: {time.time() - t0:.1f} s")
for k in TIMESCALES:
    rows_k, desc_k = write(k, probs[k])
    # semantic type: metadata only (ledger C75); none of min, max, sum, mean fits a standardized index
    tgis.register_intervals(f"eddi_{k:02d}m", HERE, rows_k, OUT_DIR / f"register_eddi_{k:02d}m.txt",
                            f"EDDI {k}-month", desc_k, semantictype="mean")
    print(f"eddi_{k:02d}m: {len(rows_k)} maps, {time.time() - t0:.0f} s so far")
ranks and probabilities for all timescales: 0.7 s
eddi_01m: 564 maps, 56 s so far
eddi_03m: 562 maps, 109 s so far
eddi_06m: 559 maps, 163 s so far
eddi_12m: 553 maps, 216 s so far

Look before moving on. Six of the maps just written: the 3-month EDDI for the windows ending August 2015 to January 2016, read back from GRASS on one diverging scale centred on 0 (red: more demand than the baseline median; blue: less). These years are inside the baseline, so values must stay inside the range section 1 printed for n = 30, and the sea must be empty. Each window shares two of its three months with the one before, so the maps should change gradually from one month to the next; a whole map that flips sign between neighbouring months would point to a window built from the wrong months. Section 6 follows this event in numbers.

pv_keys = [(2015, 8), (2015, 9), (2015, 10), (2015, 11), (2015, 12), (2016, 1)]
preview.maps([f"eddi_03m_{y}_{m_:02d}" for y, m_ in pv_keys], [f"3-month EDDI, window ending {y}-{m_:02d}" for y, m_ in pv_keys],
             "EDDI (dimensionless)", cmap="RdBu_r", center=0, ncols=3);

3-month EDDI, window ending 2015-08: 2,048 cells, 935 null; min -1.17, mean -0.05, max 1.60 EDDI (dimensionless)
3-month EDDI, window ending 2015-09: 2,048 cells, 935 null; min -1.36, mean 0.00, max 2.01 EDDI (dimensionless)
3-month EDDI, window ending 2015-10: 2,048 cells, 935 null; min -1.36, mean 0.60, max 2.01 EDDI (dimensionless)
3-month EDDI, window ending 2015-11: 2,048 cells, 935 null; min -0.67, mean 1.09, max 2.01 EDDI (dimensionless)
3-month EDDI, window ending 2015-12: 2,048 cells, 935 null; min -0.38, mean 1.04, max 2.01 EDDI (dimensionless)
3-month EDDI, window ending 2016-01: 2,048 cells, 935 null; min 0.67, mean 1.28, max 2.01 EDDI (dimensionless)

Look before moving on. The land mean of EDDI for every month of the record, at 3 and 12 months, from the probabilities in memory. Inside the baseline, each cell’s values for one calendar month are its baseline ranks turned into EDDI, which balance around 0, so the averages over the baseline months printed under the plot should be close to 0; a clearly non-zero value would mean the years ranked against were not the baseline. Outside the baseline nothing forces the values to balance, so a run of high or low years there is a result to read, not an error. The 12-month line should move more slowly than the 3-month line.

pv_ym = [(int(y), int(m_)) for y, m_ in zip(months["year"], months["month"])]
pv_eddi = {f"{k} month": np.array([np.nanmean(eddi.inverse_normal(probs[k][ym])[land]) if ym in probs[k] else np.nan
                                   for ym in pv_ym]) for k in (3, 12)}
preview.series(months["start"], pv_eddi, "EDDI (dimensionless)", title="EDDI, land mean, every month",
               xlabel="month in which the window ends")
pv_in = months["year"].isin(BASELINE).to_numpy()
print(f"mean over the baseline months ({BASELINE[0]}-{BASELINE[-1]}):",
      ", ".join(f"{lab} {np.nanmean(v[pv_in]):+.3f}" for lab, v in pv_eddi.items()))

3 month: 564 values, 2 null; min -1.97, mean -0.06, max 1.84 EDDI (dimensionless)
12 month: 564 values, 11 null; min -1.99, mean -0.11, max 1.71 EDDI (dimensionless)
mean over the baseline months (1991-2020): 3 month -0.001, 12 month -0.001

6. Categories, and one event

EDDI’s categories are percentile ranges (EDDI User Guide, p16). Dry side (ED, evaporative drought): ED0 70-80, ED1 80-90, ED2 90-95, ED3 95-98, ED4 98-100; the guide says these are “the same percentile breaks as in the US Drought Monitor”. Wet side (EW): EW0 20-30, EW1 10-20, EW2 5-10, EW3 2-5, EW4 0-2. Because EDDI rises with the percentile, each break is also a fixed EDDI value, so r.recode turns an EDDI map into a category map: * marks an open end, and a value exactly on a break goes to the upper category. r.category attaches the names and r.colors the colours.

One trap when reading the result back: the category map holds integers, and raster2numpy returns -2147483648 for an empty cell of an integer map, not NaN (ledger C91), so np.isfinite does not find the sea there.

breaks = []
for code_, label_, lo, hi in eddi.CATEGORIES:
    z_lo = None if lo == 0 else float(eddi.inverse_normal(lo / 100))
    z_hi = None if hi == 100 else float(eddi.inverse_normal(hi / 100))
    breaks.append((code_, label_, z_lo, z_hi))
fmt = lambda z: "*" if z is None else f"{z:.6f}"
rules = "\n".join(f"{fmt(lo)}:{fmt(hi)}:{code_}" for code_, _, lo, hi in breaks)
COLORS = ["#08306b", "#2171b5", "#6baed6", "#9ecae1", "#c6dbef", "#f0f0f0",
          "#fee391", "#fec44f", "#fe9929", "#d95f0e", "#993404"]
Module("r.recode", input="eddi_03m_2015_12", output="cat03_2015_12", rules="-", stdin_=rules, overwrite=True)
Module("r.category", map="cat03_2015_12", separator=":", rules="-", stdin_="\n".join(f"{c}:{l}" for c, l, _, _ in breaks))
Module("r.colors", map="cat03_2015_12", rules="-",
       stdin_="\n".join(f"{c} {int(h[1:3], 16)}:{int(h[3:5], 16)}:{int(h[5:7], 16)}" for (c, *_), h in zip(breaks, COLORS)))
pd.DataFrame([(l, c, fmt(lo), fmt(hi)) for c, l, lo, hi in breaks],
             columns=["category", "code", "EDDI from", "EDDI to"]).set_index("category")
code EDDI from EDDI to
category
EW4 -5 * -2.054189
EW3 -4 -2.054189 -1.645211
EW2 -3 -1.645211 -1.281729
EW1 -2 -1.281729 -0.841457
EW0 -1 -0.841457 -0.524002
none 0 -0.524002 0.524002
ED0 1 0.524002 0.841457
ED1 2 0.841457 1.281729
ED2 3 1.281729 1.645211
ED3 4 1.645211 2.054189
ED4 5 2.054189 *

December 2015 fell during the 2015-16 El Nino: NOAA’s Oceanic Nino Index was 2.59 for November-January (CPC ONI). The next cell draws the GRASS category map for the 3 months to December 2015 with grass.jupyter, which renders the map with the colours and category names just attached to it.

Look before moving on. The map should use only colours from the table above, leave the sea blank, and follow the EDDI map of section 4: the cells with the highest EDDI there should be in the driest categories here. A category that does not fit the cell’s EDDI value would mean a rule in the wrong order or a wrong break.

m = gj.Map(width=700)
m.d_rast(map="cat03_2015_12")
m.d_legend(raster="cat03_2015_12", title="EDDI 3-month, Dec 2015", at=(5, 60, 2, 5))
m.show()

The four timescales side by side, drawn from the probabilities in numpy with the same breaks and colours (matplotlib because it puts four maps on one figure); the cell checks that the 3-month panel equals the GRASS map above, and prints how many land cells fall in each category.

Look before moving on. The 3-month panel must look exactly like the GRASS map (the assert fails otherwise). The other panels may differ from it, since each timescale asks about a different stretch of months; what would be wrong is a category on the sea or a count table whose columns do not each add up to the number of land cells printed in section 2.

from matplotlib.colors import BoundaryNorm, ListedColormap

cat_grass = raster2numpy("cat03_2015_12").astype(float)
cat_grass[cat_grass == np.iinfo(np.int32).min] = np.nan  # integer null, see above
counts = {}
fig, axes = plt.subplots(2, 2, figsize=(11, 6.4), sharex=True, sharey=True)
for ax, k in zip(axes.flat, TIMESCALES):
    cat = eddi.category(100 * probs[k][(2015, 12)])
    if k == 3:
        assert np.array_equal(cat[land], cat_grass[land]), "numpy categories differ from the GRASS map"
    counts[f"{k} month"] = {l: int(np.sum(cat[land] == c)) for c, l, _, _ in eddi.CATEGORIES}
    im = ax.imshow(cat, cmap=ListedColormap(COLORS), norm=BoundaryNorm(np.arange(-5.5, 6.5, 1), 11), extent=EXTENT)
    ax.set_title(f"{k}-month EDDI, window ending December 2015", fontsize=10)
for ax in axes[1]:
    ax.set_xlabel("longitude")
for ax in axes[:, 0]:
    ax.set_ylabel("latitude")
cb = fig.colorbar(im, ax=axes, ticks=range(-5, 6), shrink=0.8)
cb.ax.set_yticklabels([l for _, l, _, _ in eddi.CATEGORIES])
plt.show()
pd.DataFrame(counts).loc[lambda t: t.sum(axis=1) > 0]

1 month 3 month 6 month 12 month
EW1 0 0 26 0
EW0 6 0 49 22
none 491 182 327 422
ED0 371 160 214 209
ED1 212 382 220 227
ED2 31 303 208 184
ED3 2 86 69 49

The same event through time: the share of land cells at ED1 or drier (percentile 80 or more; ED0 is the mildest dry category) for each month of 2014-2016, at each timescale. The table under the plot gives the values the text below quotes. These shares, and the counts above, are over all land cells of the study rectangle around NTT (Chapter 3), which includes parts of neighbouring islands; Chapter 6 restricts them to the cells of NTT’s districts.

Look before moving on. Every share must lie between 0 and 100%, and the lines should differ in how fast they move: the 1-month line can jump from one month to the next, the 12-month line changes slowly because consecutive windows share 11 of their 12 months.

keys = [(y, m_) for y in (2014, 2015, 2016) for m_ in range(1, 13)]
event = pd.DataFrame([{"k": k, "year": y, "month": m_, "share ED1+ %": np.mean(probs[k][(y, m_)][land] >= 0.8) * 100}
                      for k in TIMESCALES for y, m_ in keys])
event.to_csv(OUT_DIR / "share_ed1_2014_2016.csv", index=False)
fig, ax = plt.subplots(figsize=(11, 3.6))
for k in TIMESCALES:
    sub = event[event["k"] == k]
    ax.plot([dt.date(y, m_, 15) for y, m_ in zip(sub["year"], sub["month"])], sub["share ED1+ %"], label=f"{k} month", lw=1.4)
ax.set(ylabel="% of land cells, ED1 or drier", ylim=(0, 100), title=f"{AOI_NAME.upper()}: drought by EDDI, 2014-2016")
ax.legend(ncol=4)
plt.show()
table = event.pivot_table(index=["year", "month"], columns="k", values="share ED1+ %").round(1)
table.columns = [f"{k} month" for k in table.columns]
table

1 month 3 month 6 month 12 month
year month
2014 1 56.4 6.5 15.1 0.0
2 9.5 7.2 0.4 0.0
3 55.3 66.9 0.9 0.0
4 0.0 12.6 4.3 0.0
5 0.0 2.5 5.8 0.0
6 16.2 0.0 21.0 14.6
7 0.0 0.0 0.4 5.6
8 69.5 19.5 3.0 11.9
9 60.4 37.3 2.9 16.3
10 54.1 83.6 22.1 29.8
11 37.5 73.4 44.0 38.2
12 0.0 6.6 19.2 29.8
2015 1 2.8 0.0 38.9 11.3
2 0.0 0.0 15.5 5.9
3 9.3 2.2 2.7 6.6
4 0.0 2.4 0.7 12.5
5 10.7 8.8 0.4 27.4
6 8.9 4.3 11.9 26.5
7 5.2 7.3 8.9 33.2
8 1.7 3.8 8.7 18.0
9 49.3 12.8 8.8 18.3
10 65.4 42.9 33.8 23.1
11 35.3 74.4 39.3 24.0
12 22.0 69.3 44.7 41.3
2016 1 82.1 95.8 74.1 47.7
2 0.1 48.1 79.9 43.8
3 4.8 45.7 79.6 41.9
4 45.1 42.0 87.2 63.9
5 0.0 6.0 35.5 47.8
6 1.7 1.3 17.5 30.5
7 3.2 0.0 3.1 26.2
8 0.0 0.4 0.8 23.8
9 0.0 0.4 0.0 12.4
10 5.1 0.0 0.0 3.7
11 36.5 4.3 0.0 3.0
12 1.2 12.5 2.3 1.8

What the outputs show, when tested:

  • The timescale changes the picture. For the window ending in December 2015, 862 of the 1,113 land cells are in no category or ED0 at 1 month, while at 3 months 685 are ED1 or ED2 and 86 reach ED3 (the counts under the maps).
  • The event builds, peaks and fades. At 3 months the share at ED1 or drier rose from 13% in September 2015 to 74% in November and peaked at 96% in January 2016, when it was 82% at 1 month and 74% at 6 months.
  • Short windows swing, long windows remember. The 1-month share was 0.1% in February 2016 and 45% in April; the 12-month share stayed between 42% and 64% from January to May 2016, then fell month by month to 12% in September.
  • 2015-16 was not the only episode. At 3 months 84% of land was at ED1 or drier in October 2014 and 73% in November, when the Oceanic Nino Index was already 0.70 (October-December 2014).

Whether these signals matched crop or water impacts in NTT is not tested in this series.

7. Checks against other choices and another implementation

Another implementation. The eddi repository of this series’ author computes EDDI from AgERA5 with its own Python code; its output for Sumba is used here if it sits next to this repository on disk (../eddi/output). Its file for 21 December 2015 holds a 3-month window from 1 October to 31 December (its windows end at the last day of a 10-day period), the same window as here. It uses the same tall reference crop and differs in two ways: it reports a percentile defined as the share of baseline years (1991-2020) at or below the current total, and it covers only Sumba, so fewer cells overlap.

The cell computes that same percentile from this chapter’s windows and compares cell by cell. With 30 baseline years one rank place is 3.3 percentile points. What this checks is the windows and the ranks, not the plotting position or the inverse-normal step. Agreement is evidence, not proof: both start from AgERA5, so an error in AgERA5 would be in both.

repo_file = ROOT.parent / "eddi" / "output" / "idn_cli_agera5_eddi_3month_20151221.nc"
pct = (base_np <= means[3][i_dec15]).sum(0) / len(BASELINE) * 100
pct = np.where(land, pct, np.nan)
if repo_file.exists():
    ours = xr.DataArray(pct, coords={"lat": np.round(LAT, 2), "lon": np.round(LON, 2)}, dims=("lat", "lon"))
    with xr.open_dataset(repo_file) as ds:
        rep = ds["EDDI_3month"].load()
    rep = rep.assign_coords(lat=np.round(rep["lat"].values, 2), lon=np.round(rep["lon"].values, 2))
    a, b = xr.align(ours, rep, join="inner")
    ok = np.isfinite(a.values) & np.isfinite(b.values)
    diff = a.values[ok] - b.values[ok]
    print(f"{ok.sum()} cells compared: identical on {np.mean(diff == 0):.0%}; mean difference {diff.mean():+.2f}; "
          f"largest {np.abs(diff).max():.1f} percentile points ({np.abs(diff).max() / (100 / len(BASELINE)):.0f} rank places); "
          f"medians {np.median(a.values[ok]):.1f} (here) and {np.median(b.values[ok]):.1f} (repository)")
else:
    print(f"{repo_file} not found: skipping the comparison with the eddi repository")
194 cells compared: identical on 39%; mean difference -2.41; largest 43.3 percentile points (13 rank places); medians 96.7 (here) and 93.3 (repository)

When tested, the two agreed exactly on 39% of the 194 shared cells; the mean difference was -2.41 percentile points and the largest 43.3 (13 rank places), with medians of 96.7 here and 93.3 in the repository. That is a weaker match than two calculations on the same reference crop should give. An earlier test compared this series’ short-crop ETos (Chapter 4) with the same repository file: exact agreement on 78% of the cells, at most 2 rank places apart, both medians 93.3. So the repository file behaves like a short-crop result, although its metadata records the tall crop (et0_product: ETrs). One possible reason, not checked: the repository’s code reuses a saved ET0 file when one exists, and the metadata describes the setting of the run that wrote the output, not the crop of the saved file. The earlier test already checked this chapter’s windows and ranks; this one adds nothing to it until the repository output is recomputed.

Another baseline. NOAA ranks against the whole record. The cell recomputes the 3 months to December 2015 with 1979-2025 as baseline and counts the land cells whose category changes.

all_dec = np.stack([means[3][pos[(y, 12)]] for y in sorted(set(months["year"]))])
r_all, n_all = eddi.rank_in_baseline(means[3][i_dec15], all_dec, True)
p_all = eddi.tukey_probability(r_all, n_all)
cat_all, cat_base = eddi.category(100 * p_all), eddi.category(100 * probs[3][(2015, 12)])
changed = int(np.sum(cat_all[land] != cat_base[land]))
print(f"Whole record (n = {n_all}) vs {BASELINE[0]}-{BASELINE[-1]} (n = {len(BASELINE)}): category changes on "
      f"{changed} of {land.sum()} land cells ({changed / land.sum():.0%}); mean EDDI "
      f"{np.nanmean(eddi.inverse_normal(p_all)[land]):+.2f} vs {np.nanmean(eddi.inverse_normal(probs[3][(2015, 12)])[land]):+.2f}; "
      f"possible range with n = {n_all}: {float(eddi.inverse_normal(eddi.tukey_probability(1, n_all))):+.2f} to "
      f"{float(eddi.inverse_normal(eddi.tukey_probability(n_all, n_all))):+.2f}")
Whole record (n = 47) vs 1991-2020 (n = 30): category changes on 227 of 1113 land cells (20%); mean EDDI +0.99 vs +1.04; possible range with n = 47: -2.20 to +2.19

When tested, ranking against all 47 years changed the category of 227 of 1,113 land cells (20%), moved the mean EDDI from +1.04 to +0.99, and widened the possible range to -2.20 to +2.19. This series keeps 1991-2020, the WMO baseline (see Setup), also used by the eddi repository. With NOAA’s choice, values shift as years are added: “n increases as the climatology is updated with time” (Hobbins et al. 2016, p. 1749).

Look before moving on. Where the baseline choice matters: EDDI with the whole record as baseline minus EDDI with the 1991-2020 baseline, for the same window, on a scale centred on 0 (red: higher with the whole record). A correct map is empty at sea and has a value on every land cell, and the mean printed under it should equal the difference of the two mean EDDI values printed above, to rounding. Patches far from 0 are where the years outside the baseline, 1979-1990 and 2021-2025, change how unusual this window looks; the category changes counted above lie where such a shift crosses a break.

pv_diff = np.where(land, eddi.inverse_normal(p_all) - eddi.inverse_normal(probs[3][(2015, 12)]), np.nan)
preview.array_maps([pv_diff], [f"whole record minus {BASELINE[0]}-{BASELINE[-1]}, 3 months to 2015-12"],
                   "EDDI difference (dimensionless)", extent=EXTENT, cmap="RdBu_r", center=0);

whole record minus 1991-2020, 3 months to 2015-12: 2,048 cells, 935 null; min -0.43, mean -0.04, max 0.23 EDDI difference (dimensionless)

8. Checkpoint

What a later chapter needs:

  • four EDDI datasets, each with one map for every month that has a full window;
  • values only on land, checked on two months per timescale;
  • every value inside the range the plotting position allows for n = 31, so no probability reached 0 or 1;
  • the category map equal to the breaks applied to the EDDI dataset map;
  • the dataset map for December 2015 equal to the step-by-step map of section 4;
  • the event table written to paths.outputs.

The cell re-reads all of this from GRASS and paths.outputs, so it works after a restart with only Setup run. (Sections 6-7 need means and probs in memory: after a restart, run sections 2, 3 and 5 again; finished work is skipped and the rest takes seconds.)

t0 = time.time()
assert gs.gisenv()["MAPSET"] == HERE
first_month = json.loads(gs.read_command("t.rast.list", input="etrs_month", columns="name", format="json"))["data"][0]["name"]
land_ = np.isfinite(raster2numpy(first_month))
n_m = tgis.n_maps("etrs_month")
top = float(eddi.inverse_normal(eddi.tukey_probability(len(BASELINE) + 1, len(BASELINE) + 1)))
bottom = float(eddi.inverse_normal(eddi.tukey_probability(1, len(BASELINE) + 1)))
for k in TIMESCALES:
    i_ = tgis.info(f"eddi_{k:02d}m")
    assert tgis.n_maps(f"eddi_{k:02d}m") == n_m - (k - 1), f"eddi_{k:02d}m: maps missing"
    assert bottom - 1e-4 <= float(i_["min_min"]) and float(i_["max_max"]) <= top + 1e-4, f"eddi_{k:02d}m: out of range"
    for name in (f"eddi_{k:02d}m_2015_12", f"eddi_{k:02d}m_{BASELINE[0]}_06"):
        assert np.array_equal(np.isfinite(raster2numpy(name)), land_), f"{name}: nulls differ from land"
z = raster2numpy("eddi_03m_2015_12")
assert np.nanmax(np.abs(z - raster2numpy("eddi_step03_2015_12"))) < 1e-5, "dataset map differs from step-by-step map"
edges = [float(eddi.inverse_normal(lo / 100)) for _, _, lo, _ in eddi.CATEGORIES[1:]]
expected = np.digitize(z, edges) - 5.0
cat = raster2numpy("cat03_2015_12").astype(float)
cat[cat == np.iinfo(np.int32).min] = np.nan
assert np.array_equal(cat[land_], expected[land_]) and np.isnan(cat[~land_]).all(), "category map differs from the breaks"
assert len(pd.read_csv(OUT_DIR / "share_ed1_2014_2016.csv")) == 36 * len(TIMESCALES)
n_files, mb = tgis.folder_stats(PROJECT / HERE)
print(f"All checks passed. EDDI range allowed for n = {len(BASELINE) + 1}: {bottom:+.3f} to {top:+.3f}")
print(f"Mapset {HERE}: {n_files:,} files, {mb:.0f} MB | checkpoint {time.time() - t0:.0f} s | "
      f"chapter run time {time.time() - CHAPTER_START:.0f} s")
All checks passed. EDDI range allowed for n = 31: -2.033 to +2.026
Mapset ch05: 36,780 files, 18 MB | checkpoint 54 s | chapter run time 402 s

Summary

What now exists in mapset ch05:

  • etrs_month: monthly ETrs totals (mm), one map per month;
  • eddi_01m, eddi_03m, eddi_06m, eddi_12m: EDDI for the window ending in each month, baseline 1991-2020. Probabilities and percentiles are not stored as maps; section 6’s breaks table turns EDDI into categories when needed;
  • the step-by-step maps of section 4 (w03_*_12, rank03_2015_12, prob03_2015_12, eddi_step03_2015_12) and the category map cat03_2015_12, with names and colours.

On disk, in paths.outputs/ch05: the registration files and share_ed1_2014_2016.csv. In src/pgca: eddi.py, with tests in tests/test_eddi.py.

What you can now do: build a rank-based climate index from any daily dataset in GRASS, check it two ways, and read it as categories.

Chapter 6 compares El Nino years with these EDDI series, summarises them by administrative area, and exports maps and data for use outside GRASS.

Troubleshooting

Symptom Cause Fix
AssertionError: etrs does not cover the baseline Chapter 4 ran the teaching years only run Chapter 4 with run_full: true
AssertionError: a land cell has a missing day a gap in etrs re-run Chapter 4; its checkpoint checks complete days
Too many open files from t.rast.aggregate granules with many maps (not monthly sums of daily maps) lower file_limit (for example 20) so r.series runs without keeping files open
GRASS and numpy disagree only on sea cells raster2numpy returns -2147483648 for null in integer maps compare with np.iinfo(np.int32).min (section 6)
A leap February ranks unusually high at 1 month ranking totals rather than means per day pgca.eddi.window_means() (section 3)
NameError: means or probs in sections 6-7 kernel restarted run sections 2, 3 and 5 first
Memory error on a large area totals and four means arrays (section 3 prints the size) process one timescale at a time
The eddi repository comparison is skipped its output is not on your disk nothing to fix; the rest of the chapter does not need it

References