Skip to main content

Chapter 6: Analysis and Communication

Tutorial series: Climate Analysis with GRASS and Python

Chapter 6: Analysis and Communication

TipAt a glance
  • You will build: EDDI summarised for the districts of East Nusa Tenggara; a comparison of EDDI across every El Nino of 1979-2025; an animated map of one event; and the results exported as a Cloud Optimized GeoTIFF, a CF NetCDF time series and a GRASS archive, with a manifest that records how they were made.
  • You need: Chapter 4 run with run_full: true and Chapter 5 (etrs in ch04, eddi_* in ch05), and an internet connection for three small downloads (two boundary layers and NOAA’s ENSO index page, about 15 MB together; no account).
  • Time and disk: when tested on Windows 11 with 8 of 80 logical CPUs in use, 159 s in all, the preview figures included, of which reading EDDI 31 s, the animation 15 s and the district statistics 24 s. Mapset ch06 stays small (266 files, 1.6 MB); the outputs are about 2 MB.
NoteLearning objectives

After this chapter you can:

  1. Summarise rasters by district in GRASS, and say how cell size limits small districts.
  2. Select events from an external index, compare them on one footing, and test a claim against the rest of the record.
  3. Animate a time series with grass.jupyter and know its limits.
  4. Export maps and time series in formats other tools read, and check them by reading back.
  5. Record what a result was made from, so someone else can reproduce it.

Setup

The kernel starts in a new mapset, ch06, with ch04 and ch05 on the search path. As before, GRASS_OVERWRITE=0 means GRASS replaces nothing unless a call says overwrite=True; the calls here that do say so are the ones meant to be re-run. NPROCS=1 gives each GRASS tool one thread unless a call asks for more.

import datetime as dt
import io
import json
import os
import platform
import sys
import tarfile
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 boundaries, eddi, enso, provenance, tgis
from pgca import session as pg

cfg = pg.load_config(ROOT / "config.yml")
HERE = "ch06"
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 raster2numpy
from IPython.display import Image, display
from osgeo import gdal, ogr
from scipy.stats import spearmanr

gdal.UseExceptions()
ogr.UseExceptions()
path_now = gs.parse_command("g.mapsets", flags="p", format="json")["mapsets"]
for m in ("ch04", "ch05"):
    if m not in path_now:
        gs.run_command("g.mapsets", operation="add", mapset=m)
gs.run_command("g.gisenv", set="NPROCS=1")

AOI_NAME = cfg["active_aoi"]
PROJECT = Path(cfg["paths"]["grassdata"]) / cfg["grass"]["project"]
N_PARALLEL = min(8, os.cpu_count() or 1)
DL_DIR = pg.check_data_path(cfg["paths"]["downloads"])
OUT_DIR = pg.check_data_path(cfg["paths"]["outputs"]) / "ch06"
OUT_DIR.mkdir(parents=True, exist_ok=True)
GPKG, GIF = OUT_DIR / "ntt_districts.gpkg", OUT_DIR / "eddi_03m_2015_2016.gif"
COG, NC, ARCH = OUT_DIR / "eddi_03m_2015_12.tif", OUT_DIR / "eddi_03m_1979_2025.nc", OUT_DIR / "eddi_03m_2015_2016.tar.gz"
CSV_DISTRICT, CSV_EPISODES, CSV_PEAKS = (OUT_DIR / f for f in ("eddi_03m_by_district.csv", "el_nino_episodes.csv",
                                                              "district_eddi_at_peaks.csv"))
reg = gs.region()
LAT = reg["n"] - reg["nsres"] * (np.arange(reg["rows"]) + 0.5)
LON = reg["w"] + reg["ewres"] * (np.arange(reg["cols"]) + 0.5)
print("Mapset:", gs.gisenv()["MAPSET"], "| search path:", gs.parse_command("g.mapsets", flags="p", format="json")["mapsets"])
Mapset: ch06 | search path: ['ch06', 'PERMANENT', 'ch04', 'ch05']

0. Load EDDI

EDDI from Chapter 5 is read once into numpy: the 3-month and 6-month series, each map dated by the month its window ends (Chapter 5). Every later section uses these arrays (EDDI), so after a kernel restart run this cell again.

ED1_EDGE is the EDDI value at the 80th percentile, the lower edge of category ED1 (Chapter 5, section 6). This chapter writes ED1+ for “ED1 or drier”: a cell at or above the edge. EDDI is dimensionless.

Slow cell: when tested, 31 s for 1,121 maps.

def series(strds):
    rows = json.loads(gs.read_command("t.rast.list", input=strds, columns="name,start_time", format="json"))["data"]
    dates = pd.to_datetime([r["start_time"] for r in rows])
    mapset = strds.split("@")[1]
    return dates, np.stack([raster2numpy(f"{r['name']}@{mapset}") for r in rows])  # qualified: no search-path surprises


t0 = time.time()
EDDI = {k: series(f"eddi_{k:02d}m@ch05") for k in (3, 6)}
land = np.isfinite(EDDI[3][1][0])  # cells with an EDDI value: AgERA5 land cells of the study rectangle
ED1_EDGE = float(eddi.inverse_normal(0.80))
print(f"read {sum(len(v[0]) for v in EDDI.values())} maps in {time.time() - t0:.1f} s; {land.sum()} land cells; "
      f"ED1 edge EDDI {ED1_EDGE:.3f}; 3-month series {EDDI[3][0][0]:%Y-%m} to {EDDI[3][0][-1]:%Y-%m} ({len(EDDI[3][0])} months)")
read 1121 maps in 31.1 s; 1113 land cells; ED1 edge EDDI 0.841; 3-month series 1979-03 to 2025-12 (562 months)

Look before moving on. The arrays are the whole input of this chapter, so draw one month of each before using them. The cell below draws the 3-month and 6-month EDDI of December 2015 (the month the animation and the exports use later) from EDDI in memory, on one diverging colour scale centred on 0. A correct read shows sea cells empty and land values on both sides of 0 but within a few units of it, because EDDI is a rank turned into a standard normal score (Chapter 5). Panels that are entirely empty, or filled to the rectangle’s edge with no sea, would mean the wrong maps or a lost null value; in each summary line, the cell count minus the null count should equal the land cells printed above.

from pgca import preview

pv_i3 = list(EDDI[3][0]).index(pd.Timestamp("2015-12-01"))
pv_i6 = list(EDDI[6][0]).index(pd.Timestamp("2015-12-01"))
_ = preview.array_maps([EDDI[3][1][pv_i3], EDDI[6][1][pv_i6]], ["EDDI 3-month, Dec 2015", "EDDI 6-month, Dec 2015"],
                       "EDDI (dimensionless)", extent=preview.region_extent(), cmap="RdBu_r", center=0, ncols=2)

EDDI 3-month, Dec 2015: 2,048 cells, 935 null; min -0.38, mean 1.04, max 2.01 EDDI (dimensionless)
EDDI 6-month, Dec 2015: 2,048 cells, 935 null; min -1.17, mean 0.70, max 2.01 EDDI (dimensionless)

1. Districts, and what “NTT” means here

Reports and plans in Indonesia are made for districts: kabupaten (regency) and kota (city). The study area of Chapters 3-5 is a rectangle around NTT (Nusa Tenggara Timur, in English East Nusa Tenggara), and its land cells include parts of neighbouring islands. This section brings in the district boundaries, so that from here on “NTT” means the cells of NTT’s districts.

The boundaries come from geoBoundaries through its API, no account needed: the district layer (ADM2) and the province layer (ADM1), each saved once in paths.downloads/boundaries with the API’s record of source, year and licence, which the cell prints. These are geoBoundaries’ simplified geometries, small enough to download quickly; near a district border, simplification can move a cell from one district to the next.

adm2_path, adm2_meta = boundaries.geoboundaries("IDN", "ADM2", DL_DIR / "boundaries")
adm1_path, adm1_meta = boundaries.geoboundaries("IDN", "ADM1", DL_DIR / "boundaries")
for name, meta, path in (("districts (ADM2)", adm2_meta, adm2_path), ("provinces (ADM1)", adm1_meta, adm1_path)):
    print(f"{name}: {meta['admUnitCount']} units, year {meta['boundaryYearRepresented']}, source {meta['boundarySource']}; "
          f"licence {meta['boundaryLicense']}; {path.name}, {path.stat().st_size / 1e6:.1f} MB")
districts (ADM2): 519 units, year 2020, source Badan Pusat Statistik (BPS - Statistics Indonesia), World Food Programme, OCHA ROAP; licence Creative Commons Attribution 3.0 Intergovernmental Organisations (CC BY 3.0 IGO); geoBoundaries-IDN-ADM2_simplified.geojson, 11.0 MB
provinces (ADM1): 34 units, year 2017, source OpenStreetMap, Wambacher; licence Open Data Commons Open Database License 1.0; geoBoundaries-IDN-ADM1_simplified.geojson, 3.4 MB

Selecting NTT’s districts. The district layer carries names but no province, so the cell selects, in Python with OGR, the districts whose interior point lies inside the province polygon of East Nusa Tenggara. It uses PointOnSurface(), a point guaranteed to lie inside the polygon, because the centroid of a district made of several islands can fall in the sea. The selection is written to a GeoPackage with a zone number and the name.

prov_ds = ogr.Open(str(adm1_path))
prov = [f.GetGeometryRef().Clone() for f in prov_ds.GetLayer() if f.GetField("shapeName") == "East Nusa Tenggara"]
assert len(prov) == 1, "province East Nusa Tenggara not found"
src_ds = ogr.Open(str(adm2_path))
picked = sorted(((f.GetField("shapeName"), f.GetGeometryRef().Clone()) for f in src_ds.GetLayer()
                 if f.GetGeometryRef().PointOnSurface().Within(prov[0])), key=lambda t: t[0])
gpkg = GPKG
drv = ogr.GetDriverByName("GPKG")
if gpkg.exists():
    drv.DeleteDataSource(str(gpkg))
out_ds = drv.CreateDataSource(str(gpkg))
lyr = out_ds.CreateLayer("districts", srs=src_ds.GetLayer().GetSpatialRef(), geom_type=ogr.wkbMultiPolygon)
lyr.CreateField(ogr.FieldDefn("zone", ogr.OFTInteger))
lyr.CreateField(ogr.FieldDefn("name", ogr.OFTString))
for zone, (name, geom) in enumerate(picked, start=1):
    feat = ogr.Feature(lyr.GetLayerDefn())
    feat.SetField("zone", zone)
    feat.SetField("name", name)
    feat.SetGeometry(ogr.ForceToMultiPolygon(geom))
    lyr.CreateFeature(feat)
out_ds = None  # close and write
names = {zone: name for zone, (name, _) in enumerate(picked, start=1)}
print(f"{len(names)} districts in East Nusa Tenggara:", ", ".join(names.values()))
22 districts in East Nusa Tenggara: Alor, Belu, Ende, Flores Timur, Kota Kupang, Kupang, Lembata, Malaka, Manggarai, Manggarai Barat, Manggarai Timur, Nagekeo, Ngada, Rote Ndao, Sabu Raijua, Sikka, Sumba Barat, Sumba Barat Daya, Sumba Tengah, Sumba Timur, Timor Tengah Selatan, Timor Tengah Utara

Into GRASS, without an attribute table. The usual GRASS tool for district statistics, v.rast.stats, writes its results into the vector’s attribute table. On the Windows installation used for this series (the conda-forge package of GRASS 8.5), the SQLite and DBF attribute database drivers (the two tested) failed: db.execute and v.import stopped with “db_open_database() not implemented”. The cause is in how GRASS 8.5’s CMake build links the drivers on Windows, so it cannot be fixed by a setting (reported as OSGeo/grass#8291). Zonal statistics on a raster need no table, so the cell imports the districts with v.in.ogr -t (no table), takes each district’s category from the zone column (key=zone), and turns the polygons into a raster of zones (below). The names stay in Python, and r.category attaches them to the raster. If the drivers work on your installation, nothing here changes.

Every cell the coast touches. With v.to.rast alone, “a grid cell belongs to the area where the grid cell center falls into” (v.to.rast). At 0.1 degree that drops every coastal cell whose centre lies at sea, although part of the cell is land in a district and AgERA5 gives it a value; small islands lose most of their cells. GIS tools often offer an “all touched” rule instead, where every cell the polygon touches counts; v.to.rast has no such option for areas. rasterize_zones() below gets the same result in two GRASS steps:

  1. Rasterize the districts on a grid fifty times finer (0.002 degree, about 220 m; 2,500 small cells in each AgERA5 cell), inside a temporary region, so the chapter’s region is untouched.
  2. Back at 0.1 degree, r.resamp.stats method=mode gives each cell the most common zone among its small cells; small cells outside every district are null and do not count (r.resamp.stats). A cell with any district area in it therefore gets a zone, and a cell two districts share goes to the one covering most of it, so each cell still has exactly one zone. method=count gives the number of small cells inside a district, so cover is the share of each cell (0 to 1) that lies in a district.

A sliver of polygon smaller than one small cell can still be missed; that is the limit of the finer grid. When tested on NTT’s districts, grids 10, 20, 50 and 100 times finer gave a zone to 581, 597, 603 and 605 land cells, against 608 from an exact all-touched rasterization in Python (rasterio), so 50 is close and still takes under 2 s. The cell counts land cells per district and flags those with fewer than 5. That threshold is a judgement: one cell here is about 11 by 11 km, so 5 cells is about 600 km2, and a mean over fewer cells says more about the cells than about the district. r.what reads the zone of the cell at one point. Overlaps between neighbouring simplified polygons were not checked; where two overlap, the finer grid gives each small cell to one of them.

FINE = 50  # small cells per AgERA5 cell edge


def rasterize_zones(vector, output):
    # zone raster at the current region: each cell gets the zone covering most of it, if any part is in one
    gs.use_temp_region()  # region changes below stay inside this function
    Module("g.region", nsres=reg["nsres"] / FINE, ewres=reg["ewres"] / FINE)
    Module("v.to.rast", input=vector, output=f"{output}_fine", use="cat", overwrite=True)
    gs.del_temp_region()
    Module("r.resamp.stats", input=f"{output}_fine", output=f"{output}_mode", method="mode", overwrite=True)
    Module("r.resamp.stats", input=f"{output}_fine", output=f"{output}_count", method="count", overwrite=True)
    Module("r.mapcalc", expression=f"{output} = int({output}_mode)", overwrite=True)  # zones as integers (CELL)


Module("v.in.ogr", input=str(gpkg), output="districts", flags="t", key="zone", overwrite=True)
rasterize_zones("districts", "districts_r")
Module("r.category", map="districts_r", separator=":", rules="-", stdin_="\n".join(f"{z}:{n}" for z, n in names.items()))
zones = raster2numpy("districts_r").astype(float)
zones[zones == np.iinfo(np.int32).min] = np.nan  # integer null (Chapter 5, section 6)
cover = raster2numpy("districts_r_count").astype(float) / FINE**2  # share of each cell inside a district
cells = pd.Series({names[z]: int(np.sum((zones == z) & land)) for z in names}, name="land cells").sort_values()
point = gs.read_command("r.what", map="districts_r", coordinates=(123.6, -10.2), flags="f").strip().split("|")
row, col = int((reg["n"] + 10.2) / reg["nsres"]), int((123.6 - reg["w"]) / reg["ewres"])
print(f"r.what at 10.2 S, 123.6 E: zone {point[3]} ({point[4].strip()}); that cell's centre is "
      f"{LAT[row]:.2f}, {LON[col]:.2f}")
n_centre = int((land & (cover > 0) & (cover < 0.5)).sum())
print(f"land cells with a zone: {int((land & np.isfinite(zones)).sum())}, of which {n_centre} are less than half "
      f"inside the districts (the cell-centre rule would drop most of these)")
print(f"{(cells < 5).sum()} districts with fewer than 5 land cells: {', '.join(cells[cells < 5].index) or 'none'}")
cells.to_frame().T
r.what at 10.2 S, 123.6 E: zone 5 (Kota Kupang); that cell's centre is -10.20, 123.60
land cells with a zone: 603, of which 221 are less than half inside the districts (the cell-centre rule would drop most of these)
1 districts with fewer than 5 land cells: Kota Kupang
Kota Kupang Sumba Barat Sabu Raijua Malaka Manggarai Nagekeo Belu Sumba Barat Daya Sumba Tengah Ngada ... Ende Rote Ndao Timor Tengah Utara Sikka Flores Timur Timor Tengah Selatan Manggarai Barat Alor Kupang Sumba Timur
land cells 2 11 13 15 15 15 15 16 18 21 ... 24 25 27 30 32 38 50 51 60 78

1 rows × 22 columns

Look before moving on. The zone raster is what every district number below is computed from, so check it against the polygons it came from. The cell draws districts_r on the land cells (one colour per zone, its number at the middle of its cells) with the district outlines read from the GeoPackage on top. A correct raster colours every cell an outline passes through, so the coloured blocks reach past the coastline by up to one cell; it leaves land cells that no outline touches grey (no zone), and gives the smallest district, Kota Kupang, only the 2 cells counted above. Zone colours that reach well beyond an outline, or a whole island without zones, would mean the import or the rasterization used the wrong layer or key.

from pgca import preview

pv_ext = preview.region_extent()
pv_z = np.where(land, zones, np.nan)
fig, ax = plt.subplots(figsize=(10, 5.2), constrained_layout=True)
ax.imshow(np.where(land, 0.0, np.nan), extent=pv_ext, cmap="Greys", vmin=0, vmax=4, interpolation="nearest")
ax.imshow(pv_z, extent=pv_ext, cmap="nipy_spectral", vmin=0.5, vmax=len(names) + 0.5, interpolation="nearest")
pv_ds = ogr.Open(str(GPKG))  # keep the dataset open while its features are used
for pv_f in pv_ds.GetLayer():
    pv_g = pv_f.GetGeometryRef()
    for pv_k in range(pv_g.GetGeometryCount()):
        pv_ring = np.array(pv_g.GetGeometryRef(pv_k).GetGeometryRef(0).GetPoints())
        ax.plot(pv_ring[:, 0], pv_ring[:, 1], color="black", lw=0.5)
pv_f = pv_g = pv_ds = None
for pv_zone in names:
    pv_r, pv_c = np.where((zones == pv_zone) & land)
    if pv_r.size:
        ax.annotate(str(pv_zone),(LON[pv_c].mean(), LAT[pv_r].mean()), fontsize=7, ha="center", va="center",
                    bbox={"boxstyle": "round,pad=0.1", "fc": "white", "lw": 0, "alpha": 0.7})
ax.set(xlim=pv_ext[:2], ylim=pv_ext[2:], xlabel="longitude (degrees E)", ylabel="latitude (degrees N)",
       title="districts_r on land cells (colour and number: zone), district outlines from the GeoPackage; grey: other land")
plt.show()
print(preview.format_summary("districts_r on land cells", preview.summary(pv_z), "(zone number)", 0))
print(f"{(cells > 0).sum()} of {len(names)} districts have at least one land cell; zones: "
      + ", ".join(f"{z} {n}" for z, n in names.items()))

districts_r on land cells: 2,048 cells, 1,445 null; min 1, mean 12, max 22 (zone number)
22 of 22 districts have at least one land cell; zones: 1 Alor, 2 Belu, 3 Ende, 4 Flores Timur, 5 Kota Kupang, 6 Kupang, 7 Lembata, 8 Malaka, 9 Manggarai, 10 Manggarai Barat, 11 Manggarai Timur, 12 Nagekeo, 13 Ngada, 14 Rote Ndao, 15 Sabu Raijua, 16 Sikka, 17 Sumba Barat, 18 Sumba Barat Daya, 19 Sumba Tengah, 20 Sumba Timur, 21 Timor Tengah Selatan, 22 Timor Tengah Utara

NTT’s cells against the rectangle’s. NTT_MASK (land cells inside an NTT district) replaces the rectangle’s land cells from here on. To see where the other land cells of the rectangle lie, the cell also rasterizes every Indonesian district overlapping the region the same way (again without a table; only cells inside the region are written) and counts the rest: cells in other Indonesian districts, and cells in none, which here means Timor-Leste or cells AgERA5 counts as land that touch no district polygon.

NTT_MASK = land & np.isfinite(zones)
Module("v.in.ogr", input=str(adm2_path), output="idn_districts", flags="tr", overwrite=True)  # -r: only features overlapping the region (imported whole)
rasterize_zones("idn_districts", "idn_districts_r")
idn = raster2numpy("idn_districts_r").astype(float)
idn[idn == np.iinfo(np.int32).min] = np.nan
other_idn = land & ~NTT_MASK & np.isfinite(idn)
outside = land & ~np.isfinite(idn)
print(f"land cells of the rectangle: {land.sum()}; in NTT districts: {NTT_MASK.sum()}; "
      f"in other Indonesian districts: {other_idn.sum()}; in no Indonesian district: {outside.sum()}")
print(f"other Indonesian cells by longitude: {np.round(LON[np.where(other_idn)[1]].min(), 1)} to "
      f"{np.round(LON[np.where(other_idn)[1]].max(), 1)} E; no-district cells: {np.round(LON[np.where(outside)[1]].min(), 1)} to "
      f"{np.round(LON[np.where(outside)[1]].max(), 1)} E")
share = {k: pd.Series((EDDI[k][1][:, NTT_MASK] >= ED1_EDGE).mean(axis=1) * 100, index=EDDI[k][0]) for k in (3, 6)}
print(f"share of NTT land at ED1+, 3-month, mean over the baseline months 1991-2020: "
      f"{share[3]['1991':'2020'].mean():.1f}% (20% by construction for a single cell)")
land cells of the rectangle: 1113; in NTT districts: 603; in other Indonesian districts: 25; in no Indonesian district: 485
other Indonesian cells by longitude: 118.9 to 119.3 E; no-district cells: 118.9 to 125.2 E
share of NTT land at ED1+, 3-month, mean over the baseline months 1991-2020: 20.0% (20% by construction for a single cell)

When tested, 603 of the rectangle’s 1,113 land cells lie in NTT’s districts, 221 of them less than half inside; the cell-centre rule alone gave 389. Of the other 510, 25 lie in other Indonesian districts at the western edge of the rectangle (118.9-119.3 E), and 485 in no Indonesian district: Timor-Leste, and cells that AgERA5 gives a value but that contain no part of any district polygon (the two are not separated here). So many of Chapter 5’s cells lie outside NTT’s districts; every share below is over the 603. Over the baseline months, 20.0% of NTT’s cells were at ED1+ on average, as the definition of ED1 promises for each cell.

Look before moving on. The three groups of land cells counted above are drawn from the arrays the cell built (NTT_MASK, other_idn, outside), so you can see where they lie. Expect NTT’s districts to cover western Timor, Flores, Sumba and the small islands; the “other Indonesian district” cells to sit in a thin strip at the western edge of the rectangle; and the “no Indonesian district” cells in a narrow ring around every coast, and on Timor-Leste where the rectangle includes it. AgERA5 gives the ring’s cells a value, but no part of any district polygon lies in them, so even the all-touched rule gives them no zone. A coastal cell with part of an island in it belongs to a district, not to the ring. NTT cells inside Timor-Leste, or a large block of “no district” cells in the middle of Flores, would mean the district selection went wrong. The printed counts per class should equal the counts printed above.

from pgca import preview

pv_class = np.full(land.shape, np.nan)
pv_class[NTT_MASK], pv_class[other_idn], pv_class[outside] = 1, 2, 3
_ = preview.array_maps([pv_class], ["land cells of the rectangle by district"], extent=preview.region_extent(), cmap="Set2",
                       categories={1: "NTT district", 2: "other Indonesian district", 3: "no Indonesian district"},
                       panel_width=8.0, digits=0)
print("cells per class:", {k: int((pv_class == v).sum()) for k, v in (("NTT", 1), ("other Indonesian", 2), ("none", 3))})

land cells of the rectangle by district: 2,048 cells, 935 null; min 1, mean 2, max 3
cells per class: {'NTT': 603, 'other Indonesian': 25, 'none': 485}

share is a time series in its own right. For each month it holds the percentage of NTT’s 603 land cells at ED1+, for 3-month and 6-month EDDI; sections 2 and 3 are built on it. The cell draws both over the whole record (the 6-month series starts a few months later, so its first months are empty). A correct series stays between 0 and 100%, rises and falls with dry and wet spells, and has short bursts towards 100% when most of the province is in high demand at once. The 6-month curve should be smoother than the 3-month one, because each of its maps averages a longer window. A flat line at 0% or 100% would mean the mask or the ED1 edge was applied wrongly.

from pgca import preview

_ = preview.series(share[3].index, {"3-month": share[3].to_numpy(), "6-month": share[6].reindex(share[3].index).to_numpy()},
                   "% of NTT land at ED1+", title="Share of NTT's land cells at ED1+ each month", xlabel="month", digits=1)

3-month: 562 values, 0 null; min 0.0, mean 17.9, max 100.0 % of NTT land at ED1+
6-month: 562 values, 3 null; min 0.0, mean 17.1, max 100.0 % of NTT land at ED1+

2. Every El Nino of the record

ENSO, the El Nino-Southern Oscillation, is the swing of the tropical Pacific between warm (El Nino) and cool (La Nina) phases. NOAA’s Climate Prediction Center (CPC) uses the Relative Oceanic Nino Index (RONI) for official ENSO monitoring (ONI v6 page, citing NWS Public Information Statement 26-05). RONI is a 3-month running mean of ERSST.v6 sea-surface temperature anomalies in the Nino 3.4 region (5N-5S, 120-170W), minus the tropical-mean (20N-20S) anomaly, rescaled so its variance equals the original Nino 3.4 index, on a 1991-2020 base (RONI). Chapter 5 quoted the older Oceanic Nino Index (ONI) for late 2015 (2.59); RONI is lower (2.3 for the same season), because removing the tropical-mean anomaly takes out part of the warming shared by the whole tropics.

RONI is published for overlapping 3-month seasons (DJF, JFM, …). An El Nino episode is a run of at least five consecutive overlapping seasons at +0.5 C or more. The RONI page’s text says “greater than 0.5”, but its table colours 0.5 as warm, and the rule “at or above 0.5” reproduces that colouring. CPC defines no strength classes on these pages, so this chapter describes each episode by its peak value.

pgca.enso downloads the RONI page once into paths.downloads/enso, parses its table, and finds the episodes. Each season is dated by its centre month (DJF 2016 is January 2016); where several seasons share the peak value, the first is used. The cell keeps the episodes that start and end inside the EDDI record (March 1979 to December 2025).

Two dates that do not quite line up. RONI’s “December 2015” is the season November-January, centred on December; a 3-month EDDI dated December 2015 covers October-December. “Months from the RONI peak” below are therefore offset by about one month for 3-month EDDI, and more for 6-month EDDI.

roni = enso.parse_roni(enso.fetch_roni(DL_DIR / "enso").read_text(encoding="utf-8", errors="replace"))
episodes = enso.episodes(roni)
episodes = episodes[(episodes["start"] >= EDDI[3][0][0]) & (episodes["end"] <= EDDI[3][0][-1])].reset_index(drop=True)
ties = [e["label"] for _, e in episodes.iterrows()
        if (roni[(roni["date"] >= e["start"]) & (roni["date"] <= e["end"])]["roni"] == e["peak_roni"]).sum() > 1]
print(f"RONI {roni['date'].min():%Y-%m} to {roni['date'].max():%Y-%m}; {len(episodes)} El Nino episodes inside the EDDI record; "
      f"{len(ties)} with a tied peak (first used): {', '.join(ties)}")
episodes.assign(start=episodes["start"].dt.strftime("%Y-%m"), end=episodes["end"].dt.strftime("%Y-%m"),
                peak=episodes["peak"].dt.strftime("%Y-%m"))
RONI 1950-01 to 2026-09; 14 El Nino episodes inside the EDDI record; 7 with a tied peak (first used): 1982-83, 1991-92, 1997-98, 2004-05, 2006-07, 2018-19, 2023-24
start end seasons peak_roni peak label
0 1979-10 1980-02 5 0.7 1980-01 1979-80
1 1982-04 1983-06 15 2.4 1982-12 1982-83
2 1986-08 1988-01 18 1.5 1987-01 1986-88
3 1991-05 1992-07 15 2.1 1992-01 1991-92
4 1993-01 1993-10 10 1.1 1993-04 1993
5 1994-07 1995-03 9 1.3 1994-12 1994-95
6 1997-04 1998-04 13 2.3 1997-11 1997-98
7 2002-07 2003-02 8 1.3 2002-11 2002-03
8 2004-07 2005-01 7 0.7 2004-08 2004-05
9 2006-09 2007-01 5 0.9 2006-11 2006-07
10 2009-09 2010-03 7 1.5 2009-12 2009-10
11 2014-11 2016-04 18 2.3 2015-12 2014-16
12 2018-10 2019-04 7 0.8 2018-11 2018-19
13 2023-07 2024-02 8 1.4 2023-11 2023-24

Look before moving on. The episodes come from a table parsed out of a web page, so check them against the index itself. The cell draws RONI over the EDDI record with each episode shaded and the +0.5 C threshold dashed. A correct parse gives a continuous curve swinging on both sides of 0, every shaded span sitting where the curve stays at or above the dashed line for at least five seasons, and the tallest peaks matching the peak_roni column above. Gaps in the curve, or a shaded span where the curve is below the line, would mean the page was misread or the rule misapplied.

from pgca import preview

pv_roni = roni[(roni["date"] >= EDDI[3][0][0]) & (roni["date"] <= EDDI[3][0][-1])]
fig, ax = plt.subplots(figsize=(11, 3.2), constrained_layout=True)
ax.plot(pv_roni["date"], pv_roni["roni"], color="black", lw=0.8)
for _, pv_e in episodes.iterrows():
    ax.axvspan(pv_e["start"], pv_e["end"], color="#d95f0e", alpha=0.25, lw=0)
ax.axhline(0.5, color="#d95f0e", lw=0.8, ls="--")
ax.axhline(0, color="gray", lw=0.5)
ax.set(ylabel="RONI (C)", xlabel="centre month of the 3-month season",
       title="RONI over the EDDI record; shaded: El Nino episodes; dashed: +0.5 C")
ax.grid(alpha=0.3)
plt.show()
print(preview.format_summary(f"RONI {pv_roni['date'].min():%Y-%m} to {pv_roni['date'].max():%Y-%m}",
                             preview.summary(pv_roni["roni"]), "C", 1).replace(" cells", " seasons"))

RONI 1979-03 to 2025-12: 562 seasons, 0 null; min -1.9, mean -0.0, max 2.4 C

For each episode, how much of NTT’s land reached ED1+, and when? The window searched runs from the episode’s first season to six months after its last: an EDDI map summarises the 3 or 6 months ending in its month, so it still contains the episode’s last season for months afterwards. The measure is the largest monthly share in that window. Other measures would do (the mean share, or the number of months above half); the largest share is the simplest to read, and its weaknesses are tested below. Rank correlation (Spearman) is used because the shares cannot pass 100% and several lie just below it.

rows = []
for _, e in episodes.iterrows():
    span = slice(e["start"], e["end"] + pd.DateOffset(months=6))
    row = {"episode": e["label"], "peak RONI": e["peak_roni"], "RONI peak": f"{e['peak']:%Y-%m}",
           "window months": len(share[3][span])}
    for k in (3, 6):
        s = share[k][span]
        row[f"max ED1+ % ({k}-mo)"] = round(s.max(), 1)
        row[f"when ({k}-mo)"] = f"{s.idxmax():%Y-%m}"
    rows.append(row)
events = pd.DataFrame(rows).set_index("episode")
events.to_csv(OUT_DIR / "el_nino_episodes.csv")
rho, p_value = spearmanr(events["peak RONI"], events["max ED1+ % (3-mo)"])
print(f"Spearman rank correlation, peak RONI vs largest 3-month ED1+ share: {rho:+.2f} (p = {p_value:.2f}, "
      f"{len(events)} episodes); episodes at 100%: {(events['max ED1+ % (3-mo)'] >= 99.95).sum()}")
events
Spearman rank correlation, peak RONI vs largest 3-month ED1+ share: +0.10 (p = 0.75, 14 episodes); episodes at 100%: 0
peak RONI RONI peak window months max ED1+ % (3-mo) when (3-mo) max ED1+ % (6-mo) when (6-mo)
episode
1979-80 0.7 1980-01 11 38.6 1979-12 25.9 1979-12
1982-83 2.4 1982-12 21 89.1 1982-12 71.3 1983-02
1986-88 1.5 1987-01 24 94.4 1987-04 60.4 1987-05
1991-92 2.1 1992-01 21 47.6 1992-02 18.9 1991-10
1993 1.1 1993-04 16 50.6 1993-03 30.7 1993-05
1994-95 1.3 1994-12 15 74.6 1994-07 80.4 1994-09
1997-98 2.3 1997-11 19 86.7 1997-05 62.0 1998-03
2002-03 1.3 2002-11 14 97.8 2002-08 99.8 2002-08
2004-05 0.7 2004-08 13 97.3 2005-03 96.7 2005-05
2006-07 0.9 2006-11 11 97.5 2006-11 100.0 2007-01
2009-10 1.5 2009-12 13 94.0 2010-03 91.5 2010-03
2014-16 2.3 2015-12 24 97.3 2016-01 94.9 2016-04
2018-19 0.8 2018-11 13 53.6 2019-08 44.9 2019-10
2023-24 1.4 2023-11 14 99.7 2024-02 100.0 2024-02

Is that unusual? Two tests against the rest of the record:

  1. Months inside and outside the windows. Every month from March 1979 to December 2025 is either inside some episode’s window or outside all of them. The cell compares how often half or more of NTT’s land was at ED1+, and the mean share.
  2. The largest share, against windows of the same length anywhere. A long window has more chances to contain one dry month. For each episode the cell slides a window of the same length over the whole record and counts how often that window’s largest share is at least the episode’s. A low percentage means the episode’s value is unusual for a window of its length.
inside = pd.Series(False, index=share[3].index)
for _, e in episodes.iterrows():
    inside[e["start"]:e["end"] + pd.DateOffset(months=6)] = True
comp = pd.DataFrame({
    "months": [inside.sum(), (~inside).sum()],
    "months with >= 50% at ED1+ (%)": [(share[3][inside] >= 50).mean() * 100, (share[3][~inside] >= 50).mean() * 100],
    "mean share at ED1+ (%)": [share[3][inside].mean(), share[3][~inside].mean()],
}, index=["inside El Nino windows", "outside"]).round(1)
display(comp)
same_length = {}
for name, r in events.iterrows():
    rolling_max = share[3].rolling(int(r["window months"])).max().dropna()
    same_length[name] = round((rolling_max >= r["max ED1+ % (3-mo)"] - 1e-9).mean() * 100, 1)
events["same-length windows reaching it (%)"] = pd.Series(same_length)
events.to_csv(OUT_DIR / "el_nino_episodes.csv")
events[["peak RONI", "window months", "max ED1+ % (3-mo)", "same-length windows reaching it (%)"]]
months months with >= 50% at ED1+ (%) mean share at ED1+ (%)
inside El Nino windows 228 23.2 25.8
outside 334 8.7 12.5
peak RONI window months max ED1+ % (3-mo) same-length windows reaching it (%)
episode
1979-80 0.7 11 38.6 61.8
1982-83 2.4 21 89.1 43.5
1986-88 1.5 24 94.4 35.6
1991-92 2.1 21 47.6 79.3
1993 1.1 16 50.6 66.2
1994-95 1.3 15 74.6 51.1
1997-98 2.3 19 86.7 47.4
2002-03 1.3 14 97.8 11.1
2004-05 0.7 13 97.3 17.6
2006-07 0.9 11 97.5 11.1
2009-10 1.5 13 94.0 25.6
2014-16 2.3 24 97.3 30.6
2018-19 0.8 13 53.6 57.5
2023-24 1.4 14 99.7 2.6

Look before moving on. The tables are easier to judge as a picture. The next cell draws, on the left, each episode’s peak RONI against its largest share (one point per row of the table above), and on the right the share month by month around each RONI peak, with the strongest episodes (peak RONI of 2 C or more) in colour; the table under the figure lists those coloured curves. Check that every point lies between 0 and 100%, and that each coloured curve’s highest value in the table under the figure matches that episode’s “max ED1+ % (3-mo)” above (rounded), when the month of that largest share falls within the plotted months. A coloured curve that never comes near its episode’s largest share would mean the alignment on the peak month is off.

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4.2))
ax1.scatter(events["peak RONI"], events["max ED1+ % (3-mo)"], color="#d95f0e")
for name, r in events.iterrows():
    ax1.annotate(name, (r["peak RONI"], r["max ED1+ % (3-mo)"]), fontsize=8, xytext=(3, 3), textcoords="offset points")
ax1.set(xlabel="peak RONI (C)", ylabel="largest share of NTT land at ED1+ (%), 3-month", ylim=(0, 105),
        title="Episode peak vs drought extent in NTT")
colours = iter(["#d95f0e", "#7b3294", "#1b9e77", "#e7298a", "#1f78b4"])
months_rel = np.arange(-6, 13)
aligned = {}
for _, e in episodes.iterrows():
    vals = share[3].reindex([e["peak"] + pd.DateOffset(months=int(m)) for m in months_rel]).to_numpy()
    if e["peak_roni"] >= 2:
        ax2.plot(months_rel, vals, lw=2.0, color=next(colours), label=e["label"])
        aligned[e["label"]] = vals
    else:
        ax2.plot(months_rel, vals, lw=0.8, color="gray", alpha=0.5)
ax2.axhline(share[3]["1991":"2020"].mean(), color="gray", lw=0.8, ls="--", label="baseline mean")
ax2.set(xlabel="months from the RONI peak", ylabel="% of NTT land at ED1+, 3-month", ylim=(0, 105),
        title="Episodes aligned on their peak (colour: peak RONI >= 2; grey: the others)")
ax2.legend(fontsize=8)
fig.tight_layout()
plt.show()
pd.DataFrame(aligned, index=pd.Index(months_rel, name="months from peak")).round(0).T

months from peak -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12
1982-83 4.0 26.0 22.0 13.0 16.0 51.0 89.0 81.0 62.0 7.0 0.0 0.0 0.0 0.0 2.0 5.0 1.0 0.0 0.0
1991-92 11.0 7.0 4.0 17.0 0.0 6.0 28.0 48.0 26.0 0.0 0.0 0.0 6.0 8.0 1.0 0.0 0.0 4.0 6.0
1997-98 87.0 23.0 4.0 7.0 15.0 26.0 44.0 28.0 60.0 43.0 71.0 21.0 2.0 0.0 0.0 1.0 1.0 1.0 0.0
2014-16 5.0 9.0 4.0 15.0 45.0 76.0 73.0 97.0 69.0 63.0 57.0 10.0 2.0 0.0 0.0 0.0 0.0 2.0 6.0

What the outputs show, when tested:

  • Half the episodes coincided with very high demand in NTT. In 7 of the 14 episodes, 94% or more of NTT’s land reached ED1+ at 3 months at some point in the window; in 4 (1979-80, 1991-92, 1993, 2018-19) the largest share stayed between 39% and 54%. Over the whole record, months inside an El Nino window had half or more of NTT’s land at ED1+ 23.2% of the time, against 8.7% outside, and a mean share of 25.8% against 12.5%. That is an association: it does not control for the season, or for La Nina years falling outside the windows.
  • The peak of RONI did not order the episodes. The rank correlation between peak RONI and the largest share was +0.10 (p = 0.75). Episodes peaking at 2 or more reached 87-97% (1982-83, 1997-98, 2014-16), except 1991-92 (peak 2.1), which reached 48%; episodes peaking below 1 ranged from 39% (1979-80) to 97% (2004-05, 2006-07).
  • The largest share is rarely unusual for a window of that length. Windows of the same length anywhere in the record reach each episode’s largest share 2.6% (2023-24) to 79.3% (1991-92) of the time; only 2023-24 is below 10%. For the others the measure says how far an episode went, not that it went further than other periods do.
  • Timing varies. 1982-83, 1991-92 and 2014-16 had their largest share within one month of the RONI peak; 1997-98 had it in May 1997, six or seven months before (its peak value is shared by November and December 1997), with a second high of 71% in March 1998, four months after.

Fourteen episodes are few, and this chapter does not test what else drives evaporative demand in NTT.

3. One event in motion

grass.jupyter.TimeSeriesMap renders one image per map of a time series and plays them as a slider (show()), or saves them as an animated GIF (save()). This chapter keeps the GIF, because it survives in a static copy of the notebook, where a slider does not. GRASS 8.5 marks the class as “experimental and under development”: expect its options to change between versions.

The cell turns the 3-month EDDI of June 2015 to June 2016 (the RONI peak, December 2015, plus and minus six months) into category maps with r.recode, using the same breaks as Chapter 5 (pgca.eddi), and registers them in a small dataset evcat03_event. The maps are named evcat03_YYYY_MM so they do not hide Chapter 5’s cat03_2015_12 on the search path. The dataset’s semantic type is set to max because t.create needs one of min, max, sum or mean; categories are nominal, so none of them truly fits. The legend lists all 11 categories, and district outlines give the map context. Rendering is the one place NPROCS is raised, because grass.jupyter renders frames in parallel according to it; it is set back to 1 afterwards, even if rendering fails. Elsewhere, parallel runs are asked for per call.

Slow cell: rendering one frame per month; when tested, 15 s for 13 frames.

event_months = pd.date_range("2015-06-01", "2016-06-01", freq="MS")
queue = ParallelModuleQueue(nprocs=N_PARALLEL)
for d in event_months:
    queue.put(Module("r.recode", input=f"eddi_03m_{d:%Y_%m}@ch05", output=f"evcat03_{d:%Y_%m}", rules="-",
                     stdin_=eddi.recode_rules(), overwrite=True, run_=False))
queue.wait()
for d in event_months:
    Module("r.category", map=f"evcat03_{d:%Y_%m}", separator=":", rules="-", stdin_=eddi.category_label_rules())
Module("r.colors", map=[f"evcat03_{d:%Y_%m}" for d in event_months], rules="-", stdin_=eddi.category_color_rules())
tgis.register_intervals("evcat03_event", HERE,
                        [(f"evcat03_{d:%Y_%m}", d.date(), (d + pd.DateOffset(months=1)).date()) for d in event_months],
                        OUT_DIR / "register_evcat03_event.txt", "EDDI 3-month categories, 2015-16",
                        "r.recode of eddi_03m@ch05 with the Chapter 5 breaks", semantictype="max")  # categories are nominal
print(f"{len(event_months)} category maps registered in evcat03_event")
13 category maps registered in evcat03_event

Look before moving on. The category maps now exist and are registered; the animation below is their preview. The next cell renders each map of evcat03_event with TimeSeriesMap, adds the district outlines and the legend, saves the GIF and shows it. A correct animation has one frame per printed map, labelled month by month from June 2015 to June 2016, sea cells blank, the outlines lying on the coloured land, and a legend with all 11 categories. A frame that is blank or a single colour would mean an r.recode rule or a colour table did not apply to that month.

t0 = time.time()
gs.run_command("g.gisenv", set=f"NPROCS={N_PARALLEL}")  # grass.jupyter renders frames in parallel with NPROCS
try:
    tsm = gj.TimeSeriesMap(use_region=True, width=640)
    tsm.add_raster_series("evcat03_event")
    tsm.d_vect(map="districts", fill_color="none", color="gray")
    # range= widens the legend beyond the first map's own range (-1 to 2) so all 11 categories show
    tsm.d_legend(raster=f"evcat03_{event_months[0]:%Y_%m}", range=(-5, 5), use=list(range(5, -6, -1)), at=(5, 60, 2, 5),
                 title="EDDI 3-month")
    gif = GIF
    tsm.save(str(gif), duration=700)
    del tsm  # removes its temporary frame folder
finally:
    gs.run_command("g.gisenv", set="NPROCS=1")
print(f"{len(event_months)} frames rendered and saved in {time.time() - t0:.0f} s: {gif.name}, {gif.stat().st_size / 1e3:.0f} kB")
display(Image(filename=str(gif)))
13 frames rendered and saved in 15 s: eddi_03m_2015_2016.gif, 211 kB
<IPython.core.display.Image object>

Reading the animation. Each frame is one month; the label is the month the 3-month window ends. Watch where the orange (dry) categories appear, how far they spread and how long they last, and compare with the 2014-16 curve of section 2.

4. District summaries

Zonal statistics are statistics of one raster computed separately inside each zone of another raster. t.rast.univar with zones= does that for every map of a dataset: here the mean 3-month EDDI of each district for every month from March 1979 to December 2025. The cell checks one month against numpy, and checks that GRASS used as many cells per district as section 1 counted.

Slow cell: when tested, 24 s for 562 maps and 22 districts.

t0 = time.time()
out = gs.read_command("t.rast.univar", input="eddi_03m@ch05", zones="districts_r", nprocs=N_PARALLEL, separator="comma")
t_univar = time.time() - t0
table = pd.read_csv(io.StringIO(out))
for col in ("mean", "non_null_cells"):
    table[col] = pd.to_numeric(table[col], errors="coerce")
table = table[table["non_null_cells"] > 0].assign(date=lambda t: pd.to_datetime(t["start"]), zone=lambda t: t["zone"].astype(int))
table["district"] = table["zone"].map(names)
# use non_null_cells: in 8.5 the "cells" column repeats the same count (ledger C103)
counts_grass = table.groupby("district")["non_null_cells"].max()
assert all(counts_grass[d] == cells[d] for d in counts_grass.index), "GRASS cell counts differ from section 1"
district = table.pivot_table(index="date", columns="district", values="mean")
district.to_csv(OUT_DIR / "eddi_03m_by_district.csv")
z15 = EDDI[3][1][list(EDDI[3][0]).index(pd.Timestamp("2015-12-01"))]
np_mean = {names[z]: np.nanmean(z15[(zones == z) & land]) for z in names if ((zones == z) & land).any()}
diff = max(abs(district.loc["2015-12-01", d] - v) for d, v in np_mean.items())
print(f"{len(table):,} rows ({district.shape[0]} months x {district.shape[1]} districts) in {t_univar:.0f} s; "
      f"cell counts equal section 1; Dec 2015 vs numpy: max difference {diff:.1e}")
12,364 rows (562 months x 22 districts) in 24 s; cell counts equal section 1; Dec 2015 vs numpy: max difference 2.4e-07

Look before moving on. The printed check compares one month in one number; the cell below draws it. Bars are the district means of December 2015 from t.rast.univar (the district table), dots the numpy means over the same cells (np_mean), sorted from lowest to highest, with the one district of fewer than 5 cells in grey and the ED1 edge dashed. A correct table puts every dot on top of its bar, all 22 districts present. A missing bar would mean a district lost its zone; a dot off its bar, that GRASS and numpy used different cells. December 2015 is the RONI peak month of 2014-16, so apart from the grey bar these values are that episode’s column in the heatmap further down.

from pgca import preview

pv_dec = district.loc[pd.Timestamp("2015-12-01")].sort_values()
pv_x = np.arange(len(pv_dec))
fig, ax = plt.subplots(figsize=(11, 3.8), constrained_layout=True)
ax.bar(pv_x, pv_dec.to_numpy(), color=["lightgray" if cells[d] < 5 else "#d95f0e" for d in pv_dec.index],
       label="t.rast.univar (GRASS)")
ax.plot(pv_x, pd.Series(np_mean).reindex(pv_dec.index).to_numpy(), "k.", label="numpy, same cells")
ax.axhline(ED1_EDGE, color="black", lw=0.8, ls="--", label="ED1 edge")
ax.set_xticks(pv_x, pv_dec.index, rotation=60, ha="right", fontsize=8)
ax.set(ylabel="district mean EDDI (dimensionless)",
       title="3-month EDDI, December 2015, by district (grey: fewer than 5 land cells)")
ax.legend(fontsize=8, frameon=False)
ax.grid(axis="y", alpha=0.3)
plt.show()
print(preview.format_summary("district means, Dec 2015", preview.summary(pv_dec), "", 2).replace(" cells", " districts"))
print(f"districts at or above the ED1 edge: {(pv_dec >= ED1_EDGE).sum()} of {len(pv_dec)}")

district means, Dec 2015: 22 districts, 0 null; min 0.42, mean 1.09, max 1.71
districts at or above the ED1 edge: 15 of 22

District mean EDDI at each episode’s RONI peak month, as one picture: rows are districts (those with at least 5 cells), columns episodes. Red is higher demand than the baseline median (positive EDDI), blue lower; the line on the colour bar marks the ED1 edge (0.84), at and above which a district mean is in ED1 or drier. A district mean hides spread within the district; the share of a district’s cells at ED1+ would be the next measure to add.

peaks = [e["peak"] for _, e in episodes.iterrows()]
heat = district.reindex(peaks).T
heat.columns = episodes["label"]
heat = heat.loc[sorted(cells[cells >= 5].index.intersection(heat.index))]
fig, ax = plt.subplots(figsize=(12, 0.32 * len(heat) + 1.5))
im = ax.imshow(heat.to_numpy(), cmap="RdBu_r", vmin=-2, vmax=2, aspect="auto")
ax.set_xticks(range(heat.shape[1]), heat.columns, rotation=45, ha="right", fontsize=8)
ax.set_yticks(range(heat.shape[0]), heat.index, fontsize=8)
ax.set_title("District mean 3-month EDDI at each El Nino's RONI peak month")
cb = fig.colorbar(im, ax=ax, label="EDDI (red: more demand than the baseline median)", shrink=0.8)
cb.ax.axhline(ED1_EDGE, color="black", lw=1.2)
fig.tight_layout()
plt.show()
heat.to_csv(OUT_DIR / "district_eddi_at_peaks.csv")
print("districts at or above the ED1 edge, per episode:", (heat >= ED1_EDGE).sum().to_dict())
heat.round(2)

districts at or above the ED1 edge, per episode: {'1979-80': 5, '1982-83': 20, '1986-88': 0, '1991-92': 3, '1993': 8, '1994-95': 13, '1997-98': 9, '2002-03': 15, '2004-05': 16, '2006-07': 21, '2009-10': 16, '2014-16': 15, '2018-19': 0, '2023-24': 12}
label 1979-80 1982-83 1986-88 1991-92 1993 1994-95 1997-98 2002-03 2004-05 2006-07 2009-10 2014-16 2018-19 2023-24
district
Alor 0.67 1.24 -0.42 0.96 -0.32 0.83 0.48 0.91 1.13 1.70 0.92 0.79 0.37 1.76
Belu 1.34 1.37 -0.06 0.44 -0.08 0.56 0.49 0.50 -0.16 1.72 0.92 1.05 0.40 1.74
Ende 0.24 1.64 0.03 0.31 0.59 0.99 1.28 1.18 1.40 1.80 1.49 1.13 0.31 1.02
Flores Timur 0.39 1.11 0.15 0.62 -0.09 0.95 0.54 1.47 1.92 1.85 1.11 0.80 0.28 1.04
Kupang 1.19 1.51 0.53 0.55 0.78 0.69 0.56 0.77 0.65 1.87 0.78 1.14 -0.09 1.33
Lembata 0.36 1.14 0.19 0.86 -0.48 0.95 -0.02 1.27 1.96 1.78 1.11 0.65 0.15 1.39
Malaka 1.37 1.25 0.04 0.05 0.33 0.57 0.63 0.86 0.18 1.54 0.67 1.35 0.45 1.15
Manggarai -0.27 1.87 -0.41 0.75 0.68 0.99 1.53 1.07 1.56 1.74 0.78 1.52 0.41 0.83
Manggarai Barat -0.36 1.06 0.47 0.82 0.59 0.85 0.08 0.88 1.51 1.77 1.80 0.42 0.65 0.99
Manggarai Timur -0.17 1.96 -0.38 0.57 1.04 0.87 1.80 1.48 1.53 1.46 1.01 1.27 0.40 0.70
Nagekeo 0.03 1.70 0.02 0.39 0.60 1.01 1.37 1.63 1.47 1.70 1.42 0.94 0.38 0.91
Ngada -0.07 1.99 -0.25 0.38 0.88 0.90 1.56 1.54 1.38 1.63 1.01 1.11 0.47 0.67
Rote Ndao 0.43 0.89 0.37 1.18 0.78 0.15 0.15 0.12 1.32 1.81 1.58 1.37 -0.14 0.77
Sabu Raijua -0.09 0.55 0.23 0.84 0.85 -0.00 -0.51 -0.04 1.89 1.61 2.01 1.14 0.56 1.12
Sikka 0.41 1.43 0.64 0.65 -0.08 1.18 0.18 1.38 1.61 1.49 1.43 0.63 0.40 0.49
Sumba Barat -0.50 1.89 0.28 0.09 1.19 0.87 1.61 1.11 1.48 1.52 1.07 1.57 0.36 0.64
Sumba Barat Daya -0.74 0.99 0.50 0.50 1.03 1.02 1.05 1.34 1.94 1.11 1.85 0.54 0.68 -0.21
Sumba Tengah -0.16 1.92 0.46 -0.03 1.01 0.89 1.44 0.95 1.09 1.65 1.09 1.68 0.11 0.76
Sumba Timur 0.27 1.60 0.62 -0.09 0.99 0.86 1.46 1.19 1.53 1.52 1.28 1.71 0.08 0.58
Timor Tengah Selatan 1.06 1.20 0.12 0.30 0.96 0.64 0.64 0.70 0.15 1.51 0.60 1.38 0.27 1.16
Timor Tengah Utara 1.02 1.12 -0.02 0.36 0.30 0.52 0.15 0.54 0.16 1.75 0.77 1.04 0.06 1.70

When tested, 22 districts fell in East Nusa Tenggara. One has too few land cells to summarise at 0.1 degree (Kota Kupang, 2 cells) and is left out of the picture. At each episode’s RONI peak month, counting the 21 districts shown:

  • 2006-07 was at ED1 or drier in all 21 districts (district means 1.11 to 1.87), and 1982-83 in all but Sabu Raijua (0.55).
  • 2023-24 split the province: 12 of the 21 districts were at or above the ED1 edge, the highest Timor Tengah Utara, Belu and Alor (1.70 to 1.76); below it were the four Sumba districts (-0.21 to 0.76) and Sikka, Ngada, Manggarai Timur, Rote Ndao and Manggarai (0.49 to 0.83).
  • 2018-19 and 1986-88 left no district at ED1 or drier; in 2018-19 the means ranged from -0.14 to 0.68.

The RONI peak month is a common date, not each district’s worst month (section 2 shows the lags), so this is a snapshot for comparison, not a ranking of how hard each district was hit.

5. Exports

Three formats, each for a different reader. The COG and the NetCDF are read back and compared with GRASS; the archive is checked by listing its contents.

  • Cloud Optimized GeoTIFF (COG) for one map, with r.out.gdal format=COG: a GeoTIFF laid out so that a client can read parts of it over HTTP without fetching the whole file (GDAL COG driver). COMPRESS=DEFLATE is lossless compression. It is written on the AgERA5 grid, so the printed origin should equal the w and n edges of the area in config.yml.
  • NetCDF time series for the whole 3-month EDDI record, with a time axis. GRASS can write an imagery group to NetCDF with r.out.gdal, but when tested that gave one variable per map and no time axis, so this file is written with xarray from the arrays already in memory, with CF-1.8 attributes (Climate and Forecast conventions, not checked with a CF checker). grid_mapping points to a crs variable holding the coordinate system.
  • GRASS archive with t.rast.export: one GeoTIFF per map, the list of their times (list.txt), and metadata files, in one tar file. t.rast.import is the tool that reads it back into another GRASS project; that is not tested here.
cog = COG
Path(str(cog) + ".aux.xml").unlink(missing_ok=True)
# -c: no colour table (GDAL cannot store one in a Float32 GeoTIFF and would write a side file instead)
Module("r.out.gdal", input="eddi_03m_2015_12@ch05", output=str(cog), format="COG", flags="c",
       createopt=["COMPRESS=DEFLATE"], overwrite=True)
ds = gdal.Open(str(cog))
band = ds.GetRasterBand(1)
arr = band.ReadAsArray().astype(float)
nod = band.GetNoDataValue()
if nod is not None:
    arr[arr == nod] = np.nan
assert band.GetColorTable() is None and not Path(str(cog) + ".aux.xml").exists()
layout, size, gt = ds.GetMetadata("IMAGE_STRUCTURE").get("LAYOUT"), (ds.RasterXSize, ds.RasterYSize), ds.GetGeoTransform()
band = ds = None  # close the file
grass_arr = raster2numpy("eddi_03m_2015_12@ch05")
print(f"COG: layout {layout}, {size[0]} x {size[1]}, origin {gt[0]:.2f}, {gt[3]:.2f}, no colour table; "
      f"max |COG - GRASS| {np.nanmax(np.abs(arr - grass_arr)):.1e}; nulls identical: {np.array_equal(np.isnan(arr), np.isnan(grass_arr))}")
COG: layout COG, 64 x 32, origin 118.85, -7.95, no colour table; max |COG - GRASS| 0.0e+00; nulls identical: True

The NetCDF time series. The next cell builds an xarray.Dataset from the 3-month cube already in memory (EDDI[3]), with the latitudes and longitudes of the cell centres computed in Setup, writes it with compression, reads it back with xarray to compare it with the arrays, and opens it once with GDAL to see how another GIS would read it.

nc = NC
dates3, cube3 = EDDI[3]
da = xr.DataArray(cube3.astype("float32"), dims=("time", "lat", "lon"),
                  coords={"time": dates3, "lat": np.round(LAT, 4), "lon": np.round(LON, 4)}, name="eddi_03m",
                  attrs={"long_name": "Evaporative Demand Drought Index, 3-month window ending in the month",
                         "units": "1", "grid_mapping": "crs",
                         "comment": "Hobbins et al. 2016 method; ETrs (tall reference) from AgERA5 (ASCE-EWRI 2005); baseline 1991-2020"})
crs = xr.DataArray(0, attrs={"grid_mapping_name": "latitude_longitude",
                             "crs_wkt": gs.read_command("g.proj", flags="p", format="wkt").strip()})
dsx = xr.Dataset({"eddi_03m": da, "crs": crs},
                 attrs={"Conventions": "CF-1.8", "title": f"EDDI 3-month, {AOI_NAME}",
                        "source": "pygrass-climate-analysis Chapters 4-5", "history": f"written {dt.date.today()} by Chapter 6"})
dsx["time"].attrs["comment"] = "first day of the last month of each 3-month window"
dsx["lat"].attrs.update(units="degrees_north", standard_name="latitude")
dsx["lon"].attrs.update(units="degrees_east", standard_name="longitude")
dsx.to_netcdf(nc, encoding={"eddi_03m": {"zlib": True, "complevel": 4, "_FillValue": np.float32(np.nan)}})
with xr.open_dataset(nc) as back:
    d_nc = float(np.nanmax(np.abs(back["eddi_03m"].values - cube3)))
    print(f"NetCDF: {back.sizes['time']} times x {back.sizes['lat']} x {back.sizes['lon']}, "
          f"{back['time'].values[0]} to {back['time'].values[-1]}; max |file - GRASS arrays| {d_nc:.1e}; "
          f"{nc.stat().st_size / 1e6:.1f} MB")
g = gdal.Open(f'NETCDF:"{nc.as_posix()}":eddi_03m')
print(f"GDAL sees {g.RasterCount} bands, origin {g.GetGeoTransform()[0]:.2f}, {g.GetGeoTransform()[3]:.2f}")
g = None  # close, so the cell can be re-run (Windows keeps an open file locked)
NetCDF: 562 times x 32 x 64, 1979-03-01T00:00:00.000000000 to 2025-12-01T00:00:00.000000000; max |file - GRASS arrays| 0.0e+00; 1.2 MB
GDAL sees 562 bands, origin 118.85, -7.95

The GRASS archive. t.rast.export writes the maps of 2015 and 2016 from the 3-month dataset (selected with where=, an SQL condition on the start time) into one gzip-compressed tar file. The cell then lists the archive’s members by kind and prints the first line of list.txt, the file that carries each map’s time interval.

arch = ARCH
# directory= is where t.rast.export makes (and afterwards removes) its scratch folder
Module("t.rast.export", input="eddi_03m@ch05", output=str(arch), directory=str(OUT_DIR), compression="gzip", format="GTiff",
       where="start_time >= '2015-01-01' and start_time < '2017-01-01'", overwrite=True)
with tarfile.open(arch) as t:
    members = t.getnames()
    listing = t.extractfile("list.txt").read().decode().strip().splitlines()
kinds = pd.Series([Path(m).suffix or Path(m).name for m in members]).value_counts().to_dict()
print(f"{arch.name}: {len(members)} files {kinds}, {arch.stat().st_size / 1e6:.1f} MB; list.txt first line: {listing[0]}")
eddi_03m_2015_2016.tar.gz: 53 files {'.tif': 24, '.color': 24, '.txt': 5}, 0.2 MB; list.txt first line: eddi_03m_2015_01|2015-01-01 00:00:00|2015-02-01 00:00:00|eddi_03m

Look before moving on. The checks above print one number per file; the cell below reads December 2015 back from all three exports, from disk, and draws it next to the GRASS map: from the COG with GDAL, from the NetCDF with xarray (the time step 2015-12-01), and from the archive’s GeoTIFF with GDAL, reading inside the tar file through GDAL’s /vsitar/ path prefix without unpacking it. The four upper panels should look identical, with the same empty sea cells, and the three differences from GRASS should be 0 everywhere on land; the printed maximum absolute differences should be 0 and the null patterns identical. A non-zero difference would mean a loss of precision or a shifted grid in that format; a different null pattern, that a no-data value was not recognised.

from pgca import preview

pv_grass = preview.read("eddi_03m_2015_12@ch05")
pv_arrays = {}
with tarfile.open(ARCH) as pv_t:
    pv_member = next(m for m in pv_t.getnames() if Path(m).name == "eddi_03m_2015_12.tif")
for pv_label, pv_path in (("COG", str(COG)), ("archive GeoTIFF", f"/vsitar/{ARCH.as_posix()}/{pv_member}")):
    pv_ds = gdal.Open(pv_path)  # keep the handle in a variable; close it below
    pv_band = pv_ds.GetRasterBand(1)
    pv_a = pv_band.ReadAsArray().astype(float)
    pv_nod = pv_band.GetNoDataValue()
    pv_band = pv_ds = None
    if pv_nod is not None and np.isfinite(pv_nod):
        pv_a[pv_a == pv_nod] = np.nan
    pv_arrays[pv_label] = pv_a
with xr.open_dataset(NC) as pv_back:
    pv_arrays["NetCDF"] = pv_back["eddi_03m"].sel(time=pd.Timestamp("2015-12-01")).to_numpy().astype(float)
pv_ext = preview.region_extent()
_ = preview.array_maps([pv_grass, pv_arrays["COG"], pv_arrays["NetCDF"], pv_arrays["archive GeoTIFF"]],
                       ["GRASS eddi_03m_2015_12", "COG", "NetCDF, 2015-12-01", "archive GeoTIFF"], "EDDI (dimensionless)",
                       extent=pv_ext, cmap="RdBu_r", center=0, ncols=4, digits=3)
_ = preview.array_maps([pv_arrays[k] - pv_grass for k in ("COG", "NetCDF", "archive GeoTIFF")],
                       [f"{k} - GRASS" for k in ("COG", "NetCDF", "archive GeoTIFF")], "EDDI difference",
                       extent=pv_ext, cmap="RdBu_r", center=0, ncols=3, digits=3)
for pv_label, pv_a in pv_arrays.items():
    print(f"{pv_label}: max |file - GRASS| {np.nanmax(np.abs(pv_a - pv_grass)):.1e}; "
          f"nulls identical: {np.array_equal(np.isnan(pv_a), np.isnan(pv_grass))}")

GRASS eddi_03m_2015_12: 2,048 cells, 935 null; min -0.381, mean 1.038, max 2.013 EDDI (dimensionless)
COG: 2,048 cells, 935 null; min -0.381, mean 1.038, max 2.013 EDDI (dimensionless)
NetCDF, 2015-12-01: 2,048 cells, 935 null; min -0.381, mean 1.038, max 2.013 EDDI (dimensionless)
archive GeoTIFF: 2,048 cells, 935 null; min -0.381, mean 1.038, max 2.013 EDDI (dimensionless)

COG - GRASS: 2,048 cells, 935 null; min 0.000, mean 0.000, max 0.000 EDDI difference
NetCDF - GRASS: 2,048 cells, 935 null; min 0.000, mean 0.000, max 0.000 EDDI difference
archive GeoTIFF - GRASS: 2,048 cells, 935 null; min 0.000, mean 0.000, max 0.000 EDDI difference
COG: max |file - GRASS| 0.0e+00; nulls identical: True
archive GeoTIFF: max |file - GRASS| 0.0e+00; nulls identical: True
NetCDF: max |file - GRASS| 0.0e+00; nulls identical: True

6. A manifest

A result can be checked or reproduced only if you know what it was made from. The cell writes manifest.json with:

  • the software versions, and the git commit of this repository with the number of uncommitted changes (if that number is not 0, the commit alone does not describe the code that ran);
  • the config.yml in use;
  • every input dataset with its period, map count and description;
  • the downloads with their source addresses and SHA-256 checksums. A checksum is a fingerprint that changes if one byte of the file changes. NOAA revises recent RONI values, so the checksum is what pins the version of the page this run used;
  • every output with its size and checksum.

pgca.provenance holds the checksum and git helpers.

adm2_path, adm2_meta = boundaries.geoboundaries("IDN", "ADM2", DL_DIR / "boundaries")  # cached: no download
adm1_path, adm1_meta = boundaries.geoboundaries("IDN", "ADM1", DL_DIR / "boundaries")
manifest = {
    "written": dt.datetime.now().isoformat(timespec="seconds"),
    "software": {"python": platform.python_version(), "grass": gs.version()["version"], "gdal": gdal.__version__,
                 "numpy": np.__version__, "pandas": pd.__version__, "xarray": xr.__version__, "os": platform.platform()},
    "code": provenance.git_state(ROOT),
    "config": cfg,
    "inputs": {s: tgis.summary(s) for s in ("etrs@ch04", "eddi_03m@ch05", "eddi_06m@ch05")},
    "downloads": [provenance.file_entry(adm2_path, url=adm2_meta["simplifiedGeometryGeoJSON"], licence=adm2_meta["boundaryLicense"]),
                  provenance.file_entry(adm1_path, url=adm1_meta["simplifiedGeometryGeoJSON"], licence=adm1_meta["boundaryLicense"]),
                  provenance.file_entry(DL_DIR / "enso" / "roni.html", url=enso.RONI_URL)],
    "outputs": [provenance.file_entry(p) for p in (COG, NC, ARCH, GPKG, CSV_DISTRICT, CSV_EPISODES, CSV_PEAKS, GIF)],
}
(OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=1, default=str))
print(f"manifest.json: commit {str(manifest['code']['commit'])[:10]}, {manifest['code']['uncommitted_changes']} uncommitted "
      f"changes; {len(manifest['inputs'])} input datasets, {len(manifest['downloads'])} downloads, {len(manifest['outputs'])} outputs; "
      f"GRASS {manifest['software']['grass']}, GDAL {manifest['software']['gdal']}")
pd.DataFrame(manifest["outputs"]).assign(sha256=lambda t: t["sha256"].str[:12] + "...")
manifest.json: commit 0bed0c8a06, 16 uncommitted changes; 3 input datasets, 3 downloads, 8 outputs; GRASS 8.5.0, GDAL 3.12.3
file bytes sha256
0 eddi_03m_2015_12.tif 29934 a24b157b7f4f...
1 eddi_03m_1979_2025.nc 1184479 b3e36622f5c4...
2 eddi_03m_2015_2016.tar.gz 208707 56281b48dee7...
3 ntt_districts.gpkg 299008 7370a7632a93...
4 eddi_03m_by_district.csv 232563 05743a21fb64...
5 el_nino_episodes.csv 907 6dc7e791eb00...
6 district_eddi_at_peaks.csv 5555 745e8ddb2f54...
7 eddi_03m_2015_2016.gif 210670 e1adf59bb16e...

7. Checkpoint

What this chapter leaves behind, re-read from GRASS and paths.outputs, so the cell also works after a restart with only Setup run:

  • the zone raster has one category per NTT district, and the district table has a column for every district with land cells and a row for every month of the 3-month record;
  • the episode table exists and the event dataset holds 13 category maps;
  • the exports have the expected layout and sizes (their values were compared in section 5);
  • every output still matches the checksum recorded in the manifest.
t0 = time.time()
assert gs.gisenv()["MAPSET"] == HERE
gp = ogr.Open(str(GPKG))  # keep the dataset open while its layer is used
gpkg_names = {f.GetField("zone"): f.GetField("name") for f in gp.GetLayer()}
gp = None
# cats= reads the label file for every number, with or without cells (without it r.category lists only values present)
labels = gs.read_command("r.category", map="districts_r", cats=f"1-{len(gpkg_names)}", separator="pipe").strip().splitlines()
labels = {int(l.split("|")[0]): l.split("|")[1] for l in labels}
assert labels == gpkg_names, "zone raster labels differ from the districts selected"
zones_ = raster2numpy("districts_r").astype(float)
zones_[zones_ == np.iinfo(np.int32).min] = np.nan
land_ = np.isfinite(raster2numpy("eddi_03m_2015_12@ch05"))
with_cells = {int(z) for z in np.unique(zones_[land_ & np.isfinite(zones_)])}
dist = pd.read_csv(CSV_DISTRICT, index_col=0)
n_eddi = tgis.n_maps("eddi_03m@ch05")
assert dist.shape == (n_eddi, len(with_cells)), "district table incomplete"
assert len(pd.read_csv(CSV_EPISODES)) > 0
assert tgis.n_maps("evcat03_event") == 13, "event category maps missing"
cog_, nc_, arch_ = COG, NC, ARCH
ds_ = gdal.Open(str(cog_))
assert ds_.GetMetadata("IMAGE_STRUCTURE").get("LAYOUT") == "COG" and (ds_.RasterXSize, ds_.RasterYSize) == (reg["cols"], reg["rows"])
assert ds_.GetRasterBand(1).GetColorTable() is None and not Path(str(cog_) + ".aux.xml").exists()
ds_ = None
with xr.open_dataset(nc_) as back:
    assert back.sizes["time"] == n_eddi
with tarfile.open(arch_) as t:
    assert sum(m.endswith(".tif") for m in t.getnames()) == 24
m = json.loads((OUT_DIR / "manifest.json").read_text())
for entry in m["outputs"]:
    assert provenance.sha256(OUT_DIR / entry["file"]) == entry["sha256"], f"{entry['file']} changed after the manifest"
n_files, mb = tgis.folder_stats(PROJECT / HERE)
print(f"All checks passed. {len(labels)} district labels, {len(with_cells)} districts with land cells.")
print(f"Mapset {HERE}: {n_files:,} files, {mb:.1f} MB | outputs {tgis.folder_stats(OUT_DIR)[1]:.0f} MB | "
      f"checkpoint {time.time() - t0:.0f} s | chapter run time {time.time() - CHAPTER_START:.0f} s")
All checks passed. 22 district labels, 22 districts with land cells.
Mapset ch06: 266 files, 1.6 MB | outputs 2 MB | checkpoint 10 s | chapter run time 159 s

Summary

What now exists:

  • Mapset ch06: the NTT district polygons districts and their raster districts_r (with names); idn_districts and idn_districts_r for the Indonesian districts overlapping the region; the category maps evcat03_2015_06 to evcat03_2016_06 in dataset evcat03_event.
  • In paths.outputs/ch06: el_nino_episodes.csv, eddi_03m_by_district.csv, district_eddi_at_peaks.csv, ntt_districts.gpkg, the GIF, the three exports (eddi_03m_2015_12.tif, eddi_03m_1979_2025.nc, eddi_03m_2015_2016.tar.gz) and manifest.json.
  • In paths.downloads: the RONI page and the geoBoundaries layers with their API records.
  • In src/pgca: enso.py (RONI and episodes), boundaries.py (geoBoundaries) and provenance.py (checksums, git state), with tests in tests/test_enso.py and tests/test_provenance.py.

What you can now do: summarise a climate index for the units people decide in, relate it to an external driver and test the relation against the rest of the record, and hand it over in formats and with a record that others can use.

Chapter 7 turns to rainfall: when the rainy season starts in NTT, by BMKG’s rule and by a cumulative rule, with GRASS’s temporal tools for accumulation and event detection, and whether El Nino seasons start later.

Troubleshooting

Symptom Cause Fix
dbmi: db_open_database() not implemented a build problem: GRASS 8.5 built with CMake on Windows (the conda-forge package) never connects the drivers’ functions to the driver library (seen with SQLite and DBF) import with v.in.ogr -t as in section 1; zonal statistics do not need a table
ValueError: no RONI table found in the page NOAA changed the RONI page delete paths.downloads/enso/roni.html and re-run; if it persists, adapt pgca.enso.parse_roni
A district has no column in the district table at 0.1 degree it covers no land cell, or less of each of its cells than a neighbouring district does expected for very small districts; see the cell counts in section 1
province East Nusa Tenggara not found a different boundary release spells it differently print the ADM1 shapeName values and adjust the name
The GIF is not shown TimeSeriesMap is experimental in GRASS 8.5 open the GIF from paths.outputs/ch06 directly
NameError: EDDI, share or episodes kernel restarted run sections 0, 1 and 2 again (the checkpoint needs only Setup)

References