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 agera5, enso, onset, preview, tgis
from pgca import session as pg
cfg = pg.load_config(ROOT / "config.yml")
cfg["agera5"]["variables"]["precip"] = {"cds": "precipitation_flux", "statistic": None, "nc": "Precipitation_Flux",
"archive": "precip", "semantic": "sum"} # in memory only
HERE = "ch07"
pg.start(cfg, mapset=HERE)
os.environ["GRASS_OVERWRITE"] = "0"
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.abstract import Info
if "ch06" not in gs.parse_command("g.mapsets", flags="p", format="json")["mapsets"]:
gs.run_command("g.mapsets", operation="add", mapset="ch06")
gs.run_command("g.gisenv", set="NPROCS=1")Chapter 7: When the Rains Start
Tutorial series: Climate Analysis with GRASS and Python
Chapter 7: When the Rains Start
- You will build: daily AgERA5 precipitation for NTT as a GRASS time series; 10-day totals (dasarian) on the calendar BMKG uses; the start of the rainy season for every NTT land cell and season by two definitions, BMKG’s dasarian rule and a cumulative-rainfall rule, with GRASS’s
t.rast.accumulateandt.rast.accdetect; a comparison of the two; and a test of whether the rains start later in El Nino seasons. - You need: Chapter 6 (the district raster
districts_rin mapsetch06, and the RONI page it saved inpaths.downloads/enso, or a connection to NOAA) and AgERA5 precipitation for 1979-2025 (the local archive, or 47 yearly CDS downloads through the Chapter 3 helpers). The El Nino test needs every season, so this chapter always stages the full record and holds it in memory: 141 MB, and for a moment about 340 MB more while section 3 sums the dasarian and about 510 MB more during the light-rain check in section 7 (measured, ledger C113). GRASS imports 2015-2017 and builds dasarian totals for them;run_full: truewidens those two steps to 1979-2025 (17,167 daily maps plus 1,692 dasarian totals and as many sampler maps). The accumulation and onset steps in GRASS always use the teaching seasons 2015-16 and 2016-17. - Time and disk: when tested on Windows 11 with 8 of 80 logical CPUs in use, 1,036 s (about 17 minutes) with the precipitation already staged in all: staging 3 s (a first staging from the local archive took 54 s more), import and registration 52 s, dasarian totals 77 s (sampler 43 s, aggregation 34 s),
t.rast.accumulate309 s andt.rast.accdetect407 s for the two teaching seasons. Mapsetch07ends at 37,272 files and 19 MB.
After this chapter you can:
- Add a new variable to the database by reusing Chapter 3’s staging, import and labelling, and check it before use.
- Aggregate a daily series to calendar periods that are not a fixed length (dasarian) with
t.rast.aggregate.dsand a sampling dataset. - Run a cyclic accumulation with
t.rast.accumulate, detect a threshold witht.rast.accdetect, and check both against numpy. - Implement an agency rule (BMKG) and a literature rule (Naylor et al. 2007), and explain where and why they disagree.
- Test a published claim with the season, not the cell, as the unit, and say how much the test can show.
Setup
The kernel starts in a new mapset, ch07, with ch06 on the search path for the district raster. This chapter writes its precipitation maps into ch07 itself: a GRASS session writes only into its current mapset (Chapter 3, section 7), and agera5 belongs to Chapter 3.
Precipitation is not in config.yml’s variable list, because that list drives Chapter 3’s imports; the cell adds its entry to the settings in memory only. Precipitation_Flux is the variable’s name inside the AgERA5 files, in mm per day (ledger C108). As in Chapter 6, GRASS_OVERWRITE=0 means GRASS replaces nothing unless a call says overwrite=True, and NPROCS=1 gives each tool one thread unless a call asks for more, as the parallel calls here do with nprocs=NPROCS.
Seasons and years. A season here is named by the year it starts: season 2015 runs from 1 August 2015 to 31 July 2016, written 2015-16. The record 1979-2025 holds 46 complete seasons, 1979-80 to 2024-25. The baseline, against which onsets are called early or late, is the 30 seasons 1991-92 to 2020-21, as close to BMKG’s 1991-2020 normal period as whole seasons allow (ledger A45). The teaching seasons are 2015-16 and 2016-17, from teaching_years in config.yml; to close the second season and look two dasarian into the next, GRASS needs the years 2015 to 2017.
AOI_NAME = cfg["active_aoi"]
PROJECT = Path(cfg["paths"]["grassdata"]) / cfg["grass"]["project"]
RUN_FULL = bool(cfg["run_full"])
FULL_YEARS = list(range(int(cfg["period"]["start"][:4]), int(cfg["period"]["end"][:4]) + 1))
TEACH_SEASONS = list(range(cfg["teaching_years"][0], cfg["teaching_years"][1] + 1)) # season 2015 = Aug 2015 to Jul 2016
GRASS_YEARS = FULL_YEARS if RUN_FULL else list(range(TEACH_SEASONS[0], TEACH_SEASONS[-1] + 2))
SEASONS = list(range(FULL_YEARS[0], FULL_YEARS[-1])) # complete seasons: 1979-80 to 2024-25
BASE = [s for s in SEASONS if 1991 <= s <= 2020] # baseline seasons 1991-92 to 2020-21
NC, UNITS = "Precipitation_Flux", "mm d-1"
NPROCS = min(8, os.cpu_count() or 1)
STAGED = pg.check_data_path(cfg["paths"]["staged"])
DL_DIR = pg.check_data_path(cfg["paths"]["downloads"])
OUT_DIR = pg.check_data_path(cfg["paths"]["outputs"]) / "ch07"
OUT_DIR.mkdir(parents=True, exist_ok=True)
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)
EXTENT = preview.region_extent()
def strds_here():
return {s.split("@")[0] for s in gs.read_command("t.list", type="strds", where=f"mapset = '{HERE}'").split()}
print("Mapset:", HERE, "| GRASS years:", GRASS_YEARS[0], "to", GRASS_YEARS[-1], "| seasons:", SEASONS[0], "to",
SEASONS[-1], "| teaching seasons:", TEACH_SEASONS, "| full run:", RUN_FULL)Mapset: ch07 | GRASS years: 2015 to 2017 | seasons: 1979 to 2024 | teaching seasons: [2015, 2016] | full run: False
1. Two ways to say when the rains start
Farmers who depend on rain plant when the wet season has started, and a false or late start can cost them the harvest. “Start of the rainy season” sounds like an observation, but it is a definition, and different definitions give different dates for the same rain.
BMKG’s rule. Indonesia’s meteorological agency, BMKG, counts rain in dasarian, 10-day periods: days 1-10, 11-20 and 21 to the end of each month, so 36 per year and the last one of a month has 8 to 11 days. Its season bulletins define a rainy period as three consecutive dasarian with at least 50 mm each, or a total of at least 150 mm over the three, provided the first has at least 50 mm (three times 50 mm is 150 mm, so the second condition covers the first), and its onset as the first dasarian of such a period (BMKG Stasiun Klimatologi Bali, 2025; the Palembang bulletin gives the short form). In code: a dasarian starts the season if it has at least 50 mm and, with the two that follow, at least 150 mm. An older form required all three to reach 50 mm; Giarno et al. (2012) proposed the 150 mm total, searched for around the month the season normally starts; this chapter searches from 1 August instead, a second adaptation. BMKG applies the rule to station averages over a season zone (Zona Musim), an area with a clear wet and dry season, not to grid cells; applying it to each 0.1 degree cell, as this chapter does, is an adaptation. The rule is national, so it is also the one behind NTT’s season information: Giarno et al. tested both forms on Kupang rainfall and found that the 150 mm total gave a season start where the older form gave none, and in September 2026 BMKG’s outlook, issued by season zone, expected a small part of NTT to start in November and most of it in December, with a very strong El Nino under way (Distankp NTT, 2026, reporting BMKG, ledger A50; section 8 tests how El Nino moves the onset).
The cell below lists the dasarian of February 2016, a leap year, and the lengths over a whole year, using pgca.onset.dasarian_intervals(), which this chapter’s code uses throughout.
for a, b in onset.dasarian_intervals(2016, 2016)[3:6]:
print(f"{a} to {b - dt.timedelta(days=1)}: {(b - a).days} days")
lengths = pd.Series([(b - a).days for a, b in onset.dasarian_intervals(2015, 2015)]).value_counts().sort_index()
print("dasarian of 2015 by length:", ", ".join(f"{n} of {d} days" for d, n in lengths.items()))2016-02-01 to 2016-02-10: 10 days
2016-02-11 to 2016-02-20: 10 days
2016-02-21 to 2016-02-29: 9 days
dasarian of 2015 by length: 1 of 8 days, 28 of 10 days, 7 of 11 days
A cumulative rule. Naylor et al. (2007) dated onset in Java and Bali as the number of days after 1 August until accumulated rainfall reaches 200 mm, “the amount of moisture needed for crop establishment” for rice, and started on 1 August because August is typically the driest month across the archipelago. Their rule was made for rice in Java and Bali, so using their 200 mm in NTT is a choice, made so the two rules can be compared on a cited value rather than a tuned one.
GRASS has a pair of tools for the second kind of rule: t.rast.accumulate adds up a time series from a start date and starts again from zero after every cycle, a fixed period such as 12 months (section 5), and t.rast.accdetect reports when the running total enters a range. The BMKG rule needs the dasarian first, which section 3 builds with t.rast.aggregate.ds.
Neither rule checks for a false start, a dry spell soon after the start that kills a sown crop; section 7 measures how often one follows. And both read AgERA5 precipitation, which comes from the ERA5 reanalysis: ERA5 has its largest precipitation errors in the tropics and “cannot model the highest observed precipitation totals” (Lavers et al., 2022). Dates below are dates in AgERA5, not at a rain gauge.
2. Precipitation in
The Chapter 3 helpers do the work: agera5.stage_year() cuts one year of the AOI out of the local archive (or stacks the CDS downloads) into a small NetCDF file per year, and skips years already staged. All 47 years are staged, because sections 4 to 8 read every season. GRASS imports the years in GRASS_YEARS.
Slow cell on a first run without an archive (47 downloads).
t0 = time.time()
staged = {y: agera5.stage_year(cfg, "precip", y, AOI_NAME, STAGED, downloads=DL_DIR / "agera5") for y in FULL_YEARS}
t_stage = time.time() - t0
mb = sum(f.stat().st_size for f in staged.values()) / 1e6
with xr.open_dataset(staged[FULL_YEARS[0]]) as ds:
attrs = {k: ds[NC].attrs.get(k) for k in ("units", "long_name")}
print(f"staged {len(staged)} years in {t_stage:.0f} s, {mb:.1f} MB | {attrs}")staged 47 years in 3 s, 24.5 MB | {'units': 'mm d-1', 'long_name': 'Total precipitation (00-00LT)'}
Import, rename, label, register. The same three steps as Chapter 3, section 5, for one variable: r.in.gdal imports a year as one map per band (-r limits the import to the current region, -k keeps band numbers in the names; a multi-band import also records an imagery group, which the cell removes), g.rename gives each band its date, Info sets the semantic label and the units (units last, so a map with units is a finished map), and pgca.tgis.register_daily() registers each map for its day. A year counts as done when its last map has units, so the cell is safe to re-run.
def days_of(year):
return [dt.date(year, 1, 1) + dt.timedelta(days=i) for i in range((dt.date(year + 1, 1, 1) - dt.date(year, 1, 1)).days)]
have = {n.split("@")[0] for n in gs.list_strings("raster", pattern="precip_*", mapset=HERE)}
todo = [y for y in GRASS_YEARS if not (f"precip_{y}1231" in have and Info(f"precip_{y}1231", HERE).units == UNITS)]
t0 = time.time()
queue = ParallelModuleQueue(nprocs=NPROCS)
for y in todo:
queue.put(Module("r.in.gdal", input=agera5.gdal_name(staged[y], NC), output=f"precip_{y}", flags="rk",
overwrite=True, quiet=True, run_=False))
queue.wait()
for y in todo:
pairs = [x for b, d in enumerate(days_of(y), start=1) for x in (f"precip_{y}.{b}", f"precip_{d:%Y%m%d}")]
Module("g.rename", raster=pairs, overwrite=True, quiet=True)
for d in days_of(y):
info = Info(f"precip_{d:%Y%m%d}", HERE)
info.semantic_label = "precip"
info.units = UNITS
groups = [g.split("@")[0] for g in gs.list_strings("group", pattern="precip_????", mapset=HERE)] # also from interrupted runs
if groups:
Module("g.remove", type="group", name=groups, flags="f", quiet=True)
names_days = [(f"precip_{d:%Y%m%d}", d) for y in GRASS_YEARS for d in days_of(y)]
n_new = tgis.register_daily("precip", HERE, names_days, OUT_DIR / "register_precip.txt", "AgERA5 precipitation",
"Daily precipitation (AgERA5 Precipitation_Flux, mm d-1), Chapter 7", semantictype="sum")
t_import = time.time() - t0
print(f"imported {len(todo)} years, registered {n_new} new maps in {t_import:.0f} s; "
f"dataset precip: {tgis.n_maps('precip')} maps")imported 3 years, registered 1096 new maps in 52 s; dataset precip: 1096 maps
Look before moving on. One day in the dry season and one in the wet season, read back from GRASS on one colour scale in mm per day. Expect the dry-season day to be near 0 almost everywhere and the wet-season day to have rain over most islands, with the sea empty on both. Negative values, or a whole panel at one value, would mean the import or the band-to-date naming went wrong; a wet day that looks dry would point to a shifted date.
_ = preview.maps([f"precip_{TEACH_SEASONS[0]}0815", f"precip_{TEACH_SEASONS[0] + 1}0115"],
[f"{TEACH_SEASONS[0]}-08-15 (dry season)", f"{TEACH_SEASONS[0] + 1}-01-15 (wet season)"], UNITS,
cmap="Blues", ncols=2)
2015-08-15 (dry season): 2,048 cells, 935 null; min 0.00, mean 0.16, max 3.08 mm d-1
2016-01-15 (wet season): 2,048 cells, 935 null; min 0.00, mean 3.29, max 22.96 mm d-1
The full record in numpy. Sections 4 to 8 need every day of 47 years. Reading 17,000 maps from GRASS one by one is slow (Chapter 3, section 8), so the cell reads the staged files, which hold the same numbers: it checks one day against the GRASS map first. The land and NTT masks come from Chapter 6: land is where AgERA5 has values, NTT the land cells inside NTT’s districts (districts_r from Chapter 6, section 1).
t0 = time.time()
parts = []
for y in FULL_YEARS:
with xr.open_dataset(staged[y]) as ds:
parts.append(ds[NC].values.astype("float32"))
P = np.concatenate(parts)
DATES = [d for y in FULL_YEARS for d in days_of(y)]
assert P.shape == (len(DATES), reg["rows"], reg["cols"])
check_day = dt.date(TEACH_SEASONS[0] + 1, 1, 15)
diff = np.nanmax(np.abs(P[DATES.index(check_day)] - preview.read(f"precip_{check_day:%Y%m%d}")))
land = np.isfinite(P[0])
zones = preview.read("districts_r@ch06")
NTT = land & np.isfinite(zones)
print(f"read {P.shape[0]:,} days x {P.shape[1]} x {P.shape[2]} cells in {time.time() - t0:.1f} s ({P.nbytes / 1e6:.0f} MB); "
f"staged vs GRASS on {check_day}: max difference {diff:.2g} mm; land cells {land.sum()}, NTT cells {NTT.sum()}")read 17,167 days x 32 x 64 cells in 2.4 s (141 MB); staged vs GRASS on 2016-01-15: max difference 0 mm; land cells 1113, NTT cells 603
Look before moving on. The climate of the record in two pictures: the mean annual rainfall per cell over 1991-2020, and the NTT mean rainfall of each calendar month over the same years. Expect a dry season around the middle of the year and a wet season around the turn of the year; that shape is why seasons in this chapter run from 1 August to 31 July. A month near zero in the wet season, or a map with rain over the sea, would mean the wrong rows or variable were read.
idx = [i for i, d in enumerate(DATES) if 1991 <= d.year <= 2020]
Pb = P[idx]
annual = Pb.sum(axis=0) / 30
months = np.array([DATES[i].month for i in idx])
clim = [np.nanmean(Pb[months == m][:, NTT].sum(axis=0)) / 30 for m in range(1, 13)]
del Pb
_ = preview.array_maps([np.where(land, annual, np.nan)], ["mean annual rainfall 1991-2020"], "mm per year",
extent=EXTENT, cmap="YlGnBu", panel_width=6)
_ = preview.series(range(1, 13), {"NTT mean, 1991-2020": clim}, "mm per month", xlabel="month", marker="o",
title="Monthly rainfall, NTT land cells", digits=0)
order = np.argsort(clim)
print("driest months:", ", ".join(f"{pd.Timestamp(2000, m + 1, 1):%b} {clim[m]:.0f} mm" for m in order[:3]),
"| wettest:", ", ".join(f"{pd.Timestamp(2000, m + 1, 1):%b} {clim[m]:.0f} mm" for m in order[::-1][:3]))
mean annual rainfall 1991-2020: 2,048 cells, 935 null; min 677.50, mean 1334.38, max 2762.48 mm per year

NTT mean, 1991-2020: 12 values, 0 null; min 12, mean 124, max 284 mm per month
driest months: Aug 12 mm, Sep 18 mm, Jul 22 mm | wettest: Jan 284 mm, Feb 269 mm, Dec 256 mm
When tested, the driest months of 1991-2020 in the NTT mean were August (12 mm), September (18 mm) and July (22 mm), and the wettest January (284 mm), February (269 mm) and December (256 mm): a long dry season in the middle of the year and the wet season around the turn of the year.
3. Dasarian totals
t.rast.aggregate with granularity="10 days" would cut the series into blocks of exactly 10 days, which drift against the calendar: from 1 January the blocks are 1-10, 11-20 and 21-30, the 31st starts a block that runs into February, and the shift grows every month. Dasarian follow the calendar, so the cell gives GRASS the intervals explicitly. It builds a sampling dataset (a sampler for short): one small map per dasarian (a constant 1, made with r.mapcalc), registered with the dasarian’s start and end. t.rast.aggregate.ds then sums, for each interval of the sampler, the daily maps it contains (sampling=contains).
The sampler maps are made with r.mapcalc rather than copied with g.copy, for a Windows reason given under Troubleshooting. The first cell builds and registers the sampler and prints how many intervals of each length it holds.
das_iv = onset.dasarian_intervals(GRASS_YEARS[0], GRASS_YEARS[-1])
have_das = {n.split("@")[0] for n in gs.list_strings("raster", pattern="das_*", mapset=HERE)}
queue = ParallelModuleQueue(nprocs=NPROCS)
for s, _ in das_iv:
if f"das_{s:%Y%m%d}" not in have_das:
queue.put(Module("r.mapcalc", expression=f"das_{s:%Y%m%d} = 1", overwrite=True, quiet=True, run_=False))
queue.wait()
tgis.register_intervals("dasarian", HERE, [(f"das_{s:%Y%m%d}", s, e) for s, e in das_iv], OUT_DIR / "register_das.txt",
"Dasarian sampler", "One constant map per dasarian (10-day period), Chapter 7") # registers only new maps
spans = pd.Series([(e - s).days for s, e in das_iv]).value_counts().sort_index()
print(f"sampler 'dasarian': {tgis.n_maps('dasarian')} intervals,", ", ".join(f"{n} of {d} days" for d, n in spans.items()))sampler 'dasarian': 108 intervals, 2 of 8 days, 1 of 9 days, 84 of 10 days, 21 of 11 days
Aggregate over the sampler. The temporal tools used in this chapter copy the title, description and semantic type of their input into the dataset they make (from their 8.5 source code, ledger C110), so precip_das would describe itself as daily precipitation. set_labels() gives each derived dataset its own title and description and sets units on every map, as Chapters 4 and 5 did for their results.
def set_labels(strds, title, description, units, semantictype=None):
# derived datasets inherit the input's title and type: give them their own, and units on every map
Module("t.support", input=strds, title=title, description=description, quiet=True,
**({"semantictype": semantictype} if semantictype else {}))
for row in json.loads(gs.read_command("t.rast.list", input=strds, columns="name", format="json"))["data"]:
Info(row["name"], HERE).units = units
t0 = time.time()
if "precip_das" not in strds_here() or tgis.n_maps("precip_das") != len(das_iv):
Module("t.rast.aggregate.ds", input="precip", sample="dasarian", output="precip_das", basename="precip_das",
method="sum", sampling="contains", suffix="time", nprocs=NPROCS, overwrite=True, quiet=True)
set_labels("precip_das", "Dasarian precipitation", "Precipitation summed per dasarian (days 1-10, 11-20, 21-end), Chapter 7", "mm")
t_das = time.time() - t0
das_rows = json.loads(gs.read_command("t.rast.list", input="precip_das", columns="name,start_time,end_time",
format="json"))["data"]
print(f"{len(das_rows)} dasarian totals in {t_das:.0f} s; first {das_rows[0]['start_time']} to {das_rows[0]['end_time']}, "
f"last {das_rows[-1]['start_time']} to {das_rows[-1]['end_time']}")108 dasarian totals in 34 s; first 2015-01-01 00:00:00 to 2015-01-11 00:00:00, last 2017-12-21 00:00:00 to 2018-01-01 00:00:00
The same totals in numpy, for every year. pgca.onset.dasarian_sums() adds up the daily stack over the same intervals for the whole record. Before it is trusted, the cell compares it with the GRASS totals for every dasarian GRASS made: the largest difference should be at the level of single-precision rounding (hundredths of a millimetre or less), and the null cells identical.
DAS_IV, DAS = onset.dasarian_sums(P, DATES)
pos = {s: k for k, (s, _) in enumerate(DAS_IV)}
worst, same_nulls = 0.0, True
for r in das_rows:
g = preview.read(r["name"])
n = DAS[pos[dt.date.fromisoformat(r["start_time"][:10])]]
worst = max(worst, float(np.nanmax(np.abs(g - n))))
same_nulls &= bool((np.isnan(g) == np.isnan(n)).all())
print(f"numpy: {len(DAS_IV)} dasarian {DAS_IV[0][0]} to {DAS_IV[-1][1] - dt.timedelta(days=1)}; "
f"GRASS vs numpy over {len(das_rows)} dasarian: max difference {worst:.2g} mm, same nulls: {same_nulls}")numpy: 1692 dasarian 1979-01-01 to 2025-12-31; GRASS vs numpy over 108 dasarian: max difference 0 mm, same nulls: True
Look before moving on. The dasarian totals of two teaching seasons at three cells, one on Timor near Kupang, one on Sumba near Waingapu and one in the Flores highlands near Ruteng, with the 50 mm line of the BMKG rule. ntt_cell() picks the NTT land cell nearest to a given latitude and longitude. Expect each cell to start near zero in August, cross 50 mm somewhere between October and January, and stay above it for weeks in the wet season. A series that never rises, or rises in July, would point to a misread location or a shifted calendar.
def ntt_cell(lat, lon):
rr, cc = np.where(NTT)
k = np.argmin((LAT[rr] - lat) ** 2 + (LON[cc] - lon) ** 2)
return int(rr[k]), int(cc[k])
PLACES = {"near Kupang": ntt_cell(-10.17, 123.61), "near Waingapu": ntt_cell(-9.65, 120.26), "near Ruteng": ntt_cell(-8.61, 120.46)}
k0, k1 = pos[dt.date(TEACH_SEASONS[0], 8, 1)], pos[dt.date(TEACH_SEASONS[-1] + 1, 8, 1)]
x = [s for s, _ in DAS_IV[k0:k1]]
fig, ax = plt.subplots(figsize=(10, 3.2), constrained_layout=True)
for place, (r, c) in PLACES.items():
ax.step(x, DAS[k0:k1, r, c], where="post", label=f"{place} ({LAT[r]:.2f}, {LON[c]:.2f})", lw=1)
ax.axhline(50, color="grey", ls="--", lw=0.8)
ax.set(ylabel="mm per dasarian", title="Dasarian totals, teaching seasons")
ax.legend(fontsize=8, frameon=False)
plt.show()
for place, (r, c) in PLACES.items():
print(f"{place}: {np.sum(DAS[k0:k1, r, c] >= 50)} of {k1 - k0} dasarian at or above 50 mm")
near Kupang: 16 of 72 dasarian at or above 50 mm
near Waingapu: 15 of 72 dasarian at or above 50 mm
near Ruteng: 37 of 72 dasarian at or above 50 mm
Is 1 August a fair season start? A season should start in the dry season, or an early start is missed. For each NTT cell, the cell finds the driest dasarian of the calendar year on average over 1991-2020. If most cells have their driest dasarian in August or September, starting the count on 1 August is safe; cells whose driest period comes before August would deserve a different start.
cal = np.array([(s.month - 1) * 3 + (s.day > 10) + (s.day > 20) for s, _ in DAS_IV])
inbase = np.array([1991 <= s.year <= 2020 for s, _ in DAS_IV])
clim_das = np.stack([DAS[inbase & (cal == k)].mean(axis=0) for k in range(36)])
driest = np.where(NTT, np.nanargmin(np.where(np.isnan(clim_das), np.inf, clim_das), axis=0), -1)
month_of = driest[NTT] // 3 + 1
counts = pd.Series(month_of).value_counts().sort_index()
print("NTT cells by the month of their driest dasarian (1991-2020):",
", ".join(f"{pd.Timestamp(2000, m, 1):%b} {n}" for m, n in counts.items()))
jul = NTT & (driest // 3 + 1 == 7)
if jul.any():
aug1 = clim_das[21][jul] # 1-10 August, mean 1991-2020
print(f"the {jul.sum()} July cells: driest dasarian {sorted({int(k) % 3 + 1 for k in driest[jul]})} of July (1 = days 1-10); "
f"1-10 August mean {aug1.mean():.1f} mm (max {aug1.max():.1f} mm), against the 50 mm a BMKG onset needs")
_ = preview.array_maps([np.where(NTT, driest // 3 + 1, np.nan)], ["month of the driest dasarian, 1991-2020"], "month",
extent=EXTENT, categories={m: f"{pd.Timestamp(2000, m, 1):%b}" for m in sorted(counts.index)},
cmap="tab10", panel_width=7, digits=0)NTT cells by the month of their driest dasarian (1991-2020): Jul 32, Aug 489, Sep 82
the 32 July cells: driest dasarian [3] of July (1 = days 1-10); 1-10 August mean 1.6 mm (max 3.2 mm), against the 50 mm a BMKG onset needs

month of the driest dasarian, 1991-2020: 2,048 cells, 1,445 null; min 7, mean 8, max 9 month
When tested, 571 of the 603 NTT cells had their driest dasarian in August (489) or September (82), and 32 in July. For those 32 the driest dasarian is the last of July (21-31 July), and 1-10 August still averaged only 1.6 mm there over 1991-2020 (3.2 mm at most), far below the 50 mm a BMKG onset needs, so 1 August still falls in their dry season. Section 4 counts how often a season starts in its very first dasarian, the case a later season start would have missed.
4. Onset by BMKG’s rule
For each season (1 August to 31 July, 36 dasarian), onset.bmkg_onset() looks for the first dasarian with at least 50 mm whose total with the next two reaches 150 mm. A season that starts in its last two dasarian may need the first ones of the next season, so the cell passes two more. No qualifying dasarian means no onset that season: stored as -1 and counted, not hidden. The onset date is the first day of the dasarian, and the chapter measures it in days after 1 August, which runs across the new year without a break (day 153 is 1 January).
The rule lives in src/pgca/onset.py (bmkg_onset()), with tests in tests/test_onset.py. Its core is three lines on the stack of dasarian totals d, where a, b and c are each dasarian and the two after it:
a, b, c = d[:-2], d[1:-1], d[2:]
ok = (a >= 50) & (a + b + c >= 150) # bulletin form
ok = (a >= 50) & (b >= 50) & (c >= 50) # older strict formand the onset is the first dasarian where ok is true. The cell runs both forms for every NTT cell and every season of the record. A cell-season is one cell in one season: 603 NTT cells times 30 baseline seasons give 18,090. A season without onset counts as later than any season with one when medians are taken, because the rains did not start before the season ended.
def das_days(season, n=36):
starts = [s for s, _ in DAS_IV]
k = starts.index(dt.date(season, 8, 1))
return np.array([(s - dt.date(season, 8, 1)).days for s in starts[k:k + n]])
ONSET_B = np.stack([onset.bmkg_onset(onset.season_dasarian(DAS_IV, DAS, s)) for s in SEASONS])
ONSET_S = np.stack([onset.bmkg_onset(onset.season_dasarian(DAS_IV, DAS, s), strict=True) for s in SEASONS])
DAY_B = np.stack([np.where(ONSET_B[i] >= 0, das_days(s)[np.clip(ONSET_B[i], 0, 35)], -1) for i, s in enumerate(SEASONS)])
ib = [SEASONS.index(s) for s in BASE]
def on_date(day):
return f"{dt.date(2001, 8, 1) + dt.timedelta(days=int(day)):%d %b}"
for name, o in (("bulletin rule", ONSET_B), ("strict rule", ONSET_S)):
v = o[ib][:, NTT]
d = np.stack([np.where(o[i] >= 0, das_days(s)[np.clip(o[i], 0, 35)], 400) for i, s in zip(ib, BASE)])[:, NTT]
print(f"{name}: no onset in {np.mean(v < 0) * 100:.1f}% of NTT cell-seasons 1991-2020; median onset "
f"{on_date(np.median(d))}; onset in the first dasarian (1-10 Aug): {np.sum(v == 0)}") # no onset = 400, latest
print(f"the two forms give different dasarian in {np.mean(ONSET_B[ib][:, NTT] != ONSET_S[ib][:, NTT]) * 100:.1f}% of cell-seasons")bulletin rule: no onset in 1.1% of NTT cell-seasons 1991-2020; median onset 21 Nov; onset in the first dasarian (1-10 Aug): 9
strict rule: no onset in 11.3% of NTT cell-seasons 1991-2020; median onset 01 Dec; onset in the first dasarian (1-10 Aug): 0
the two forms give different dasarian in 42.4% of cell-seasons
When tested, the bulletin rule found an onset in all but 1.1% of NTT cell-seasons of 1991-2020, with a median onset of 21 November; the older strict rule left 11.3% without onset and moved the median to 1 December, and the two forms put the onset in different dasarian in 42.4% of cell-seasons. The choice of wording in a bulletin is not a detail. Only 9 cell-seasons started in the first dasarian, 1-10 August, so the season start of 1 August cuts off almost nothing.
The same rule in GRASS, for one season. As a check that the numpy rule says what the bulletin says, the cell writes it once as a single r.mapcalc expression on the 38 dasarian maps of the first teaching season (36 plus 2 of the next). The expression is a chain of if(): the onset is dasarian 0 if dasarian 0 qualifies, else 1 if dasarian 1 qualifies, and so on; null() if none does. So the map holds the index of the dasarian (0 = 1-10 August), not days. It is compared with the numpy result cell by cell.
s0 = TEACH_SEASONS[0]
row_by_start = {r["start_time"][:10]: r["name"] for r in das_rows}
starts = [s for s, _ in DAS_IV]
k = starts.index(dt.date(s0, 8, 1))
nm = [row_by_start[str(s)] for s in starts[k:k + 38]]
expr = "null()"
for j in range(35, -1, -1):
a, b, c = nm[j], nm[j + 1], nm[j + 2]
expr = f"if({a} >= 50 && {a} + {b} + {c} >= 150, {j}, {expr})"
Module("r.mapcalc", expression=f"onset_bmkg_{s0} = {expr}", overwrite=True, quiet=True)
Info(f"onset_bmkg_{s0}", HERE).units = "dasarian index (0 = 1-10 August)"
g = preview.read(f"onset_bmkg_{s0}")
n = ONSET_B[SEASONS.index(s0)].astype(float)
n[n < 0] = np.nan
agree = np.sum(((g == n) | (np.isnan(g) & np.isnan(n))) & land)
print(f"onset_bmkg_{s0}: expression of {len(expr):,} characters; GRASS and numpy agree on {agree} of {land.sum()} land "
f"cells (and on {np.sum(((g == n) | (np.isnan(g) & np.isnan(n))) & NTT)} of {NTT.sum()} NTT cells)")onset_bmkg_2015: expression of 5,504 characters; GRASS and numpy agree on 1113 of 1113 land cells (and on 603 of 603 NTT cells)
Look before moving on. BMKG onset for the two teaching seasons and the median over 1991-2020, in days after 1 August, on one colour scale (day 92 is 1 November, day 122 is 1 December, day 153 is 1 January). Expect the pattern to follow the annual rainfall map of section 2, with later onset where that map is drier, and NTT cells with no onset to show as empty. A map that is uniform, or onsets in August across whole islands, would point to an error in the rule or the season start.
def on_map(day_arr):
return np.where(NTT & (day_arr >= 0), day_arr, np.nan)
med_b = np.where(NTT, np.median(np.where(DAY_B[ib] >= 0, DAY_B[ib], 400), axis=0), np.nan) # no onset ranks latest
med_b[med_b >= 400] = np.nan
_ = preview.array_maps([on_map(DAY_B[SEASONS.index(s)]) for s in TEACH_SEASONS] + [med_b],
[f"BMKG onset {s}-{(s + 1) % 100:02d}" for s in TEACH_SEASONS] + ["median 1991-2020"],
"days after 1 August", extent=EXTENT, cmap="viridis_r", digits=0)
BMKG onset 2015-16: 2,048 cells, 1,458 null; min 102, mean 143, max 184 days after 1 August
BMKG onset 2016-17: 2,048 cells, 1,445 null; min 41, mean 103, max 173 days after 1 August
median 1991-2020: 2,048 cells, 1,445 null; min 81, mean 117, max 218 days after 1 August
When tested, the 2015-16 season (an El Nino season, section 8) started about 40 days later than 2016-17 in the mean over NTT cells with an onset (day 143 against day 103). In the median map, which runs from day 81 (21 October) to day 218 (early March, a few coastal cells on the south coast of Flores), onset came earliest in western Flores and inland Timor, among the wetter areas of the annual map, and latest on the small southern islands and along the coasts, among the drier ones. The match with the annual map is rough, not cell by cell.
5. Cumulative rainfall with t.rast.accumulate
t.rast.accumulate walks through the dataset one granularity step at a time from start, adds each step’s value to the running total, writes one map per step, and starts again from zero every cycle. Its methods come from r.series.accumulate, built for degree days; method="mean" adds the mean of the maps in each step, which with one daily map per 1-day step is that day’s rain. So the output is a running sum of rain since 1 August, restarted every 12 months.
Two details that trip people up (ledger C110):
limitsis required even thoughmethod="mean"does not use it; pygrass wants it as a tuple,(0, 1).- A day without an input map gets no output map; the next day continues from the last total.
The cell runs both teaching seasons in one call; the second season begins when the 12-month cycle restarts on 1 August.
Slow cell: GRASS starts one r.series.accumulate per day, so 731 runs here; when tested, 309 s.
acc_start, acc_stop = f"{TEACH_SEASONS[0]}-08-01", f"{TEACH_SEASONS[-1] + 1}-08-01"
n_days = (dt.date.fromisoformat(acc_stop) - dt.date.fromisoformat(acc_start)).days
info = tgis.info("precip")
assert info["start_time"][:10] <= acc_start and info["end_time"][:10] >= acc_stop, "precip must cover every cycle"
REBUILT = set() # datasets rebuilt in this kernel: anything made from them is rebuilt too
t0 = time.time()
if "precip_acc" not in strds_here() or tgis.n_maps("precip_acc") != n_days:
Module("t.rast.accumulate", input="precip", output="precip_acc", basename="precip_acc", start=acc_start,
stop=acc_stop, cycle="12 months", granularity="1 day", method="mean", limits=(0, 1), suffix="time",
overwrite=True, quiet=True)
set_labels("precip_acc", "Accumulated precipitation", "Precipitation summed from 1 August, restarted every 12 months, Chapter 7", "mm")
REBUILT.add("precip_acc")
t_acc = time.time() - t0
acc_rows = json.loads(gs.read_command("t.rast.list", input="precip_acc", columns="name,start_time", format="json"))["data"]
acc_by_day = {dt.date.fromisoformat(r["start_time"][:10]): r["name"] for r in acc_rows}
print(f"precip_acc: {len(acc_rows)} maps in {t_acc:.0f} s, {acc_rows[0]['start_time'][:10]} to {acc_rows[-1]['start_time'][:10]}")precip_acc: 731 maps in 309 s, 2015-08-01 to 2017-07-31
Check against numpy. The running sum in numpy is one line (np.cumsum over the days of the season). The cell compares GRASS and numpy on the first and last day of each season and on 31 December. Differences of a fraction of a millimetre after a season are rounding: the numpy check sums single-precision values, GRASS adds in double precision.
def season_slice(season):
i0 = DATES.index(dt.date(season, 8, 1))
return slice(i0, DATES.index(dt.date(season + 1, 8, 1)))
for s in TEACH_SEASONS:
cum = np.cumsum(P[season_slice(s)], axis=0)
for d in (dt.date(s, 8, 1), dt.date(s, 12, 31), dt.date(s + 1, 7, 31)):
k = (d - dt.date(s, 8, 1)).days
dmax = np.nanmax(np.abs(preview.read(acc_by_day[d]) - cum[k]))
print(f"season {s}: {d} (day {k}): max |GRASS - numpy| {dmax:.2g} mm; NTT mean so far {np.nanmean(cum[k][NTT]):.0f} mm")season 2015: 2015-08-01 (day 0): max |GRASS - numpy| 0 mm; NTT mean so far 0 mm
season 2015: 2015-12-31 (day 152): max |GRASS - numpy| 0.00011 mm; NTT mean so far 261 mm
season 2015: 2016-07-31 (day 365): max |GRASS - numpy| 0.00091 mm; NTT mean so far 1222 mm
season 2016: 2016-08-01 (day 0): max |GRASS - numpy| 0 mm; NTT mean so far 0 mm
season 2016: 2016-12-31 (day 152): max |GRASS - numpy| 0.00034 mm; NTT mean so far 588 mm
season 2016: 2017-07-31 (day 364): max |GRASS - numpy| 0.0024 mm; NTT mean so far 1679 mm
Look before moving on. The running totals at the three cells of section 3 through both teaching seasons, with the 200 mm threshold of the cumulative rule. The curves are the numpy totals, which the cell above has just checked against GRASS; the two maps below are read from GRASS. Each curve should rise slowly through the dry months, steeply in the wet season, and drop to zero on 1 August when the cycle restarts. The day each curve crosses 200 mm is that cell’s onset by the cumulative rule; section 6 finds it with GRASS.
days = sorted(acc_by_day)
fig, ax = plt.subplots(figsize=(10, 3.2), constrained_layout=True)
for place, (r, c) in PLACES.items():
total = np.concatenate([np.cumsum(P[season_slice(s), r, c]) for s in TEACH_SEASONS])
ax.plot(days, total, label=place, lw=1)
ax.axhline(200, color="grey", ls="--", lw=0.8)
ax.set(ylabel="mm since 1 August", title="Running total of rain, teaching seasons")
ax.legend(fontsize=8, frameon=False)
plt.show()
_ = preview.maps([acc_by_day[dt.date(s, 12, 31)] for s in TEACH_SEASONS],
[f"rain 1 Aug to 31 Dec {s}" for s in TEACH_SEASONS], "mm", cmap="YlGnBu", ncols=2)

rain 1 Aug to 31 Dec 2015: 2,048 cells, 935 null; min 73.16, mean 225.98, max 646.21 mm
rain 1 Aug to 31 Dec 2016: 2,048 cells, 935 null; min 198.94, mean 497.73, max 1340.86 mm
6. Onset with t.rast.accdetect
t.rast.accdetect reads an accumulation and writes two datasets for the same cycles:
- occurrence: for each day and cell where the running total lies inside
range, the number of days since the cycle started (1 August = 0); null elsewhere. Days where no cell is in the range produce no map at all, so the dataset starts at the first day any cell qualifies; - indicator: 1 on the day a cell enters the range, 2 while it stays, 3 on the last day inside the range before it leaves. A running total of rain never falls, so with this range only 1 and 2 occur.
The upper bound 100000 mm only says “no upper limit” (no cell gets anywhere near it). With range=(200, 100000) the occurrence is “days since 1 August, for every day the total is above 200 mm”, so its smallest value in a season is the onset. The test is strictly greater than the lower bound (ledger C110), which onset.cumulative_onset() copies. The indicator is written to show the tool’s second output; the chapter’s onset comes from the occurrence, and the cell prints which indicator values occur.
Slow cell: when tested, 407 s for the two seasons.
t0 = time.time()
stale = "precip_acc" in REBUILT or not {"precip_occ", "precip_ind"} <= strds_here()
if stale or tgis.n_maps("precip_occ") != tgis.n_maps("precip_ind"):
Module("t.rast.accdetect", input="precip_acc", occurrence="precip_occ", indicator="precip_ind", basename="precip_det",
start=acc_start, stop=acc_stop, cycle="12 months", range=(200, 100000), suffix="time", overwrite=True,
quiet=True)
set_labels("precip_occ", "Onset occurrence", "Days since 1 August while accumulated precipitation is above 200 mm, Chapter 7", "days")
set_labels("precip_ind", "Onset indicator", "1 start, 2 inside, 3 last day inside the 200 mm range, Chapter 7", "class")
REBUILT.add("precip_occ")
t_det = time.time() - t0
occ_rows = json.loads(gs.read_command("t.rast.list", input="precip_occ", columns="name,start_time", format="json"))["data"]
ind_rows = json.loads(gs.read_command("t.rast.list", input="precip_ind", columns="name", format="json"))["data"]
ind_values = sorted({int(v) for r in ind_rows[::30] for v in np.unique(preview.read(r["name"])) if np.isfinite(v)})
print(f"precip_occ: {len(occ_rows)} maps in {t_det:.0f} s; first {occ_rows[0]['start_time'][:10]}, last {occ_rows[-1]['start_time'][:10]}; "
f"precip_ind: {len(ind_rows)} maps, values in every 30th map: {ind_values}")precip_occ: 561 maps in 407 s; first 2015-11-27, last 2017-07-31; precip_ind: 561 maps, values in every 30th map: [1, 2]
From occurrence to one onset map per season. The smallest occurrence value of a season is its onset, and finding a minimum over an interval is again an aggregation over a sampler: a second sampling dataset with one interval per season (1 August to 1 August), and t.rast.aggregate.ds method=minimum. t.rast.aggregate with granularity="12 months" would not do: it aligns its intervals with the month of the first map of the dataset (the first precip_occ date printed above), not with 1 August.
for s in TEACH_SEASONS:
if not gs.find_file(f"season_{s}", element="cell", mapset=HERE)["name"]:
Module("r.mapcalc", expression=f"season_{s} = 1", overwrite=True, quiet=True)
tgis.register_intervals("season", HERE, [(f"season_{s}", dt.date(s, 8, 1), dt.date(s + 1, 8, 1)) for s in TEACH_SEASONS],
OUT_DIR / "register_season.txt", "Season sampler", "1 August to 1 August, Chapter 7")
if "precip_occ" in REBUILT or "onset_cum" not in strds_here() or tgis.n_maps("onset_cum") != len(TEACH_SEASONS):
Module("t.rast.aggregate.ds", input="precip_occ", sample="season", output="onset_cum", basename="onset_cum",
method="minimum", sampling="contains", suffix="time", overwrite=True, quiet=True)
set_labels("onset_cum", "Onset, cumulative rule", "Days after 1 August until precipitation since then exceeds 200 mm, Chapter 7",
"days", semantictype="min")
on_rows = json.loads(gs.read_command("t.rast.list", input="onset_cum", columns="name,start_time", format="json"))["data"]
print(f"onset_cum: {len(on_rows)} maps:", ", ".join(r["name"] for r in on_rows))onset_cum: 2 maps: onset_cum_2015_08_01T00_00_00, onset_cum_2016_08_01T00_00_00
GRASS against numpy, and the whole record. onset.cumulative_onset() runs the same rule in numpy (a running sum, strictly above 200 mm) for every season of the record. For the teaching seasons the cell compares it with the GRASS maps cell by cell; if they agree everywhere, the numpy version can stand in for GRASS over the 46 seasons.
CUM_DAY = np.stack([onset.cumulative_onset(P[season_slice(s)], 200) for s in SEASONS])
for r in on_rows:
s = int(r["start_time"][:4])
g, n = preview.read(r["name"]), CUM_DAY[SEASONS.index(s)].astype(float)
n[n < 0] = np.nan
ok = np.sum(((g == n) | (np.isnan(g) & np.isnan(n))) & land)
print(f"{r['name']}: GRASS and numpy onset agree on {ok} of {land.sum()} land cells; NTT median onset {on_date(np.nanmedian(g[NTT]))}")onset_cum_2015_08_01T00_00_00: GRASS and numpy onset agree on 1113 of 1113 land cells; NTT median onset 25 Dec
onset_cum_2016_08_01T00_00_00: GRASS and numpy onset agree on 1113 of 1113 land cells; NTT median onset 26 Nov
Look before moving on. The GRASS onset of each teaching season, then the difference GRASS minus numpy, which must be 0 on every land cell (the summary lines print its minimum and maximum).
gr = [preview.read(r["name"]) for r in on_rows]
nu = [np.where(CUM_DAY[SEASONS.index(int(r["start_time"][:4]))] >= 0, CUM_DAY[SEASONS.index(int(r["start_time"][:4]))], np.nan)
for r in on_rows]
_ = preview.array_maps([np.where(NTT, g, np.nan) for g in gr], [r["name"] for r in on_rows], "days after 1 August",
extent=EXTENT, cmap="viridis_r", digits=0)
_ = preview.array_maps([np.where(land, g - n, np.nan) for g, n in zip(gr, nu)], [f"{r['name']}: GRASS - numpy" for r in on_rows],
"days", extent=EXTENT, cmap="RdBu_r", center=0, digits=0)
onset_cum_2015_08_01T00_00_00: 2,048 cells, 1,445 null; min 118, mean 151, max 188 days after 1 August
onset_cum_2016_08_01T00_00_00: 2,048 cells, 1,445 null; min 52, mean 103, max 153 days after 1 August

onset_cum_2015_08_01T00_00_00: GRASS - numpy: 2,048 cells, 935 null; min 0, mean 0, max 0 days
onset_cum_2016_08_01T00_00_00: GRASS - numpy: 2,048 cells, 935 null; min 0, mean 0, max 0 days
How much does the threshold matter? 200 mm was carried over from rice in Java and Bali, so the cell repeats the cumulative rule in numpy with 100, 150 and 250 mm and prints the median onset of 1991-2020 for each.
for thr in (100, 150, 200, 250):
d = np.stack([onset.cumulative_onset(P[season_slice(s)], thr) for s in BASE])[:, NTT]
d_all = np.stack([onset.cumulative_onset(P[season_slice(s)], thr) for s in SEASONS])[:, NTT]
print(f"threshold {thr} mm: median onset {on_date(np.median(d[d >= 0]))}; no onset in {np.sum(d < 0)} of {d.size} "
f"cell-seasons 1991-2020 and {np.sum(d_all < 0)} of {d_all.size} in all 46 seasons")threshold 100 mm: median onset 21 Nov; no onset in 0 of 18090 cell-seasons 1991-2020 and 0 of 27738 in all 46 seasons
threshold 150 mm: median onset 30 Nov; no onset in 0 of 18090 cell-seasons 1991-2020 and 0 of 27738 in all 46 seasons
threshold 200 mm: median onset 06 Dec; no onset in 0 of 18090 cell-seasons 1991-2020 and 0 of 27738 in all 46 seasons
threshold 250 mm: median onset 12 Dec; no onset in 0 of 18090 cell-seasons 1991-2020 and 0 of 27738 in all 46 seasons
When tested, the GRASS onset equalled the numpy onset on all 1,113 land cells in both teaching seasons, so the numpy version stands in for GRASS over the whole record. The threshold moves the median onset of 1991-2020 by 6 to 9 days per 50 mm: 21 November at 100 mm, 30 November at 150 mm, 6 December at 200 mm and 12 December at 250 mm, and no NTT cell-season was left without an onset at any of the four thresholds, in all 46 seasons. The 200 mm used below is Naylor et al.’s, not a value fitted to NTT.
7. Two definitions compared
To compare like with like, the cumulative onset is converted to the dasarian it falls in, and each NTT cell-season of 1991-2020 is put in one class: the same dasarian, one apart, earlier or later by more, or no onset by one or both rules.
def to_das(day_arr, season):
edges = das_days(season)
return np.where(day_arr >= 0, np.searchsorted(edges, day_arr, side="right") - 1, -1)
CUM_DAS = np.stack([to_das(CUM_DAY[i], s) for i, s in enumerate(SEASONS)])
bmkg_base_ntt, cum_base_ntt = ONSET_B[ib][:, NTT], CUM_DAS[ib][:, NTT]
both = (bmkg_base_ntt >= 0) & (cum_base_ntt >= 0)
dd = cum_base_ntt - bmkg_base_ntt
table = pd.Series({"same dasarian": np.sum(both & (dd == 0)), "cumulative 1 later": np.sum(both & (dd == 1)),
"cumulative 1 earlier": np.sum(both & (dd == -1)), "cumulative 2+ later": np.sum(both & (dd >= 2)),
"cumulative 2+ earlier": np.sum(both & (dd <= -2)), "no onset by one or both": np.sum(~both)})
print((table / table.sum() * 100).round(1).astype(str) + "%", f"\n(of {table.sum()} NTT cell-seasons, 1991-2020)")
print(f"one dasarian apart: {np.mean(both & (abs(dd) == 1)) * 100:.1f}%; two or more apart: {np.mean(both & (abs(dd) >= 2)) * 100:.1f}%; "
f"cumulative later by any amount: {np.mean(both & (dd > 0)) * 100:.1f}%")same dasarian 33.8%
cumulative 1 later 37.9%
cumulative 1 earlier 3.2%
cumulative 2+ later 18.8%
cumulative 2+ earlier 5.2%
no onset by one or both 1.1%
dtype: str
(of 18090 NTT cell-seasons, 1991-2020)
one dasarian apart: 41.2%; two or more apart: 24.0%; cumulative later by any amount: 56.7%
When tested, the two rules put onset in the same dasarian in 33.8% of NTT cell-seasons, one dasarian apart in 41.2% and two or more apart in 24.0%; the cumulative rule was the later one in 56.7%. Only 1.1% had no onset by one rule or both. Two features of the rules push the same way: 200 mm since 1 August is more rain than the 150 mm that can open a BMKG season, and BMKG dates onset at the start of its wet window, before those 150 mm have fallen, while the cumulative rule dates it on the day the total is passed.
Look before moving on. Where the rules differ: the median over 1991-2020 of cumulative minus BMKG onset per cell, in dasarian (positive: the cumulative rule is later), and the NTT median onset of every season by both rules. After the table above, expect mostly positive values (the cumulative rule later), and look for where the sign flips: cells where light rain before the season adds up to 200 mm before any dasarian reaches 50 mm would show the cumulative rule earlier. The second figure shows whether the two rules move together from season to season.
import warnings
with warnings.catch_warnings(): # cells with no season where both rules found an onset give an all-NaN median
warnings.simplefilter("ignore", RuntimeWarning)
med_diff = np.nanmedian(np.where((ONSET_B[ib] >= 0) & (CUM_DAS[ib] >= 0), CUM_DAS[ib] - ONSET_B[ib], np.nan), axis=0)
med_diff = np.where(NTT, med_diff, np.nan)
_ = preview.array_maps([med_diff], ["median of cumulative minus BMKG onset, 1991-2020"], "dasarian", extent=EXTENT,
cmap="RdBu_r", center=0, panel_width=7, digits=1)
def ntt_median(day_arr):
v = np.where(day_arr[NTT] >= 0, day_arr[NTT], 400.0) # no onset ranks latest
m = float(np.median(v))
return m if m < 400 else np.nan
SEASON_B = np.array([ntt_median(DAY_B[i]) for i in range(len(SEASONS))])
SEASON_C = np.array([ntt_median(CUM_DAY[i]) for i in range(len(SEASONS))])
_ = preview.series(SEASONS, {"BMKG rule": SEASON_B, "cumulative 200 mm": SEASON_C}, "days after 1 August", marker="o",
title="NTT median onset per season", xlabel="season (year it starts)", digits=0)
print(f"correlation of the two rules' season medians: {np.corrcoef(SEASON_B, SEASON_C)[0, 1]:.2f}")
median of cumulative minus BMKG onset, 1991-2020: 2,048 cells, 1,445 null; min -2.5, mean 0.8, max 1.0 dasarian

BMKG rule: 46 values, 0 null; min 61, mean 117, max 153 days after 1 August
cumulative 200 mm: 46 values, 0 null; min 69, mean 127, max 156 days after 1 August
correlation of the two rules' season medians: 0.87
When tested, the NTT median onset ranged over 92 days from season to season with the BMKG rule (day 61 to 153) and 87 days with the cumulative rule (69 to 156), and the two series had a correlation of 0.87: the rules disagree on the date, but largely agree on which seasons started early or late.
Light rain. A cumulative rule adds every drop, so days with a little rain count towards it; the cell first prints how many NTT cell-days of the baseline have some rain but less than 1 mm. Then it sets every day below 1 mm to 0 and runs both rules again. The 1 mm cut is this chapter’s choice, not a correction of the data; the result shows how sensitive each rule is to the smallest amounts, not which is right. The cell makes a second copy of the record in memory and deletes it at the end.
light = np.mean([np.mean((P[i][NTT] > 0) & (P[i][NTT] < 1)) for i in idx]) * 100
print(f"NTT cell-days 1991-2020 with 0 < P < 1 mm: {light:.1f}%")
P1 = np.where(P < 1.0, 0.0, P)
_, DAS1 = onset.dasarian_sums(P1, DATES)
b1 = np.stack([onset.bmkg_onset(onset.season_dasarian(DAS_IV, DAS1, s)) for s in BASE])[:, NTT]
c1 = np.stack([onset.cumulative_onset(P1[season_slice(s)], 200) for s in BASE])[:, NTT]
c0 = CUM_DAY[ib][:, NTT]
ok = (c1 >= 0) & (c0 >= 0)
print(f"days < 1 mm set to 0: BMKG onset unchanged in {np.mean(b1 == bmkg_base_ntt) * 100:.1f}% of NTT cell-seasons; cumulative onset later "
f"in {np.mean(c1[ok] > c0[ok]) * 100:.1f}%, median shift {np.median(c1[ok] - c0[ok]):+.0f} days, 90th percentile "
f"{np.percentile(c1[ok] - c0[ok], 90):+.0f} days")
del P1, DAS1NTT cell-days 1991-2020 with 0 < P < 1 mm: 36.3%
days < 1 mm set to 0: BMKG onset unchanged in 97.6% of NTT cell-seasons; cumulative onset later in 84.2%, median shift +2 days, 90th percentile +5 days
False starts. A start is only useful if rain continues. For each NTT cell-season of 1991-2020 the cell finds the longest run of days with less than 1 mm in the 30 days after onset, and counts how often that run reaches 10 days. For the BMKG rule the 30 days start after the three dasarian the rule itself required to be wet, otherwise the check would partly test the rule against itself; for the cumulative rule they start the day after onset. Ten days is a judgement, not a standard: long enough for a newly sown crop to suffer in a hot dry spell. The histogram shows the whole distribution, so a different cut can be read off it.
spells = {"BMKG rule": [], "cumulative 200 mm": []}
for i, s in zip(ib, BASE):
i0 = DATES.index(dt.date(s, 8, 1))
sl = P[i0:i0 + 420] # the season and the weeks after it, for late onsets
after_b = np.where(NTT & (ONSET_B[i] >= 0), das_days(s, 39)[np.clip(ONSET_B[i] + 3, 0, 38)] - 1, -1)
spells["BMKG rule"].append(onset.longest_dry_spell(sl, after_b)[NTT])
spells["cumulative 200 mm"].append(onset.longest_dry_spell(sl, np.where(NTT, CUM_DAY[i], -1))[NTT])
spells = {k: np.concatenate(v) for k, v in spells.items()}
for k, v in spells.items():
v = v[v >= 0]
print(f"{k}: a dry spell of 10+ days within 30 days of onset in {np.mean(v >= 10) * 100:.1f}% of {v.size} cell-seasons")
_ = preview.array_hist({k: v[v >= 0] for k, v in spells.items()}, "longest dry spell after onset (days)", bins=np.arange(0, 31) - 0.5,
title="Longest run of days < 1 mm in the 30 days after onset, NTT 1991-2020", digits=0)BMKG rule: a dry spell of 10+ days within 30 days of onset in 0.6% of 17898 cell-seasons
cumulative 200 mm: a dry spell of 10+ days within 30 days of onset in 0.9% of 18090 cell-seasons

BMKG rule: 17,898 values; min 0, mean 2, max 19 longest dry spell after onset (days)
cumulative 200 mm: 18,090 values; min 0, mean 2, max 14 longest dry spell after onset (days)
When tested, 36.3% of NTT cell-days of 1991-2020 had some rain but less than 1 mm. Setting days below 1 mm to 0 left the BMKG onset unchanged in 97.6% of cell-seasons and delayed the cumulative onset in 84.2%, by a median of 2 days (90th percentile 5 days): light rain matters little to a rule that starts from a wet dasarian, and a little, consistently, to a rule that adds everything up. A dry spell of 10 days or more in the 30-day window followed 0.6% of BMKG onsets and 0.9% of cumulative ones, so in AgERA5 such a break after either onset was rare over NTT. Whether that holds at a single farm is beyond what a 0.1 degree reanalysis can say (section 1).
8. Do the rains start later in El Nino seasons?
Naylor et al. (2007) state that “El Niño events typically lead to delayed rainfall” in Indonesia’s main rice-growing regions. That is the claim tested here for NTT, with three groups of seasons taken from NOAA’s Relative Oceanic Nino Index (RONI, Chapter 6): a season is an El Nino season if September-November of its first year belongs to an El Nino episode (RONI at or above +0.5 C for at least five overlapping seasons, Chapter 6, section 2), a La Nina season if it belongs to a La Nina episode (the same rule at or below -0.5 C), and neutral otherwise. September-November is used because it comes before or at the onset; a season classified by later months would mix cause and effect.
The unit is the season, not the cell: the 603 NTT cells of one season are strongly correlated (the same monsoon, the same ENSO state), so counting cells would overstate the evidence. Each season gets one number, the NTT median of the onset anomaly, in days, against each cell’s 1991-2020 median (no onset ranks as latest). The difference between the El Nino median and the median of the other seasons is tested with a permutation test: shuffle the group labels many times and count how often a difference at least as large, in either direction (two-sided), appears by chance. Like Chapter 6’s comparison with windows of the same length, it builds the chance distribution from the data themselves. It assumes the seasons are exchangeable, which a trend in onset over 1979-2024 would break. The shuffles are random, so p itself varies a little from run to run; the table repeats each test with a second random seed to show by how much.
roni = enso.parse_roni(enso.fetch_roni(DL_DIR / "enso").read_text(encoding="utf-8"))
nino = enso.episodes(roni)
nina = enso.episodes(roni.assign(roni=-roni["roni"]))
son = {s: pd.Timestamp(s, 10, 1) for s in SEASONS} # SON is centred on October
def in_episode(t, eps):
return any((e["start"] <= t) & (t <= e["end"]) for _, e in eps.iterrows())
group = pd.Series({s: "El Nino" if in_episode(son[s], nino) else "La Nina" if in_episode(son[s], nina) else "neutral"
for s in SEASONS})
print(group.value_counts().to_string(), "\nEl Nino seasons:", ", ".join(f"{s}-{(s + 1) % 100:02d}" for s in group.index[group == "El Nino"]))La Nina 16
El Nino 15
neutral 15
El Nino seasons: 1979-80, 1982-83, 1986-87, 1987-88, 1991-92, 1993-94, 1994-95, 1997-98, 2002-03, 2004-05, 2006-07, 2009-10, 2015-16, 2018-19, 2023-24
The test. For each season and rule, the next cell takes every NTT cell’s onset minus that cell’s 1991-2020 median and summarises the season by the median over its cells. It then compares El Nino seasons with all other seasons, and with neutral seasons only, since La Nina seasons in the “others” would make any contrast larger.
def anomalies(day_arr):
v = np.where(day_arr >= 0, day_arr, 400.0)[:, NTT] # no onset ranks latest
base = np.median(v[ib], axis=0)
return pd.Series(np.median(v - base, axis=1), index=SEASONS)
ANOM = {"BMKG rule": anomalies(DAY_B), "cumulative 200 mm": anomalies(CUM_DAY)}
is_nino = (group == "El Nino").to_numpy()
rows = []
for rule, a in ANOM.items():
for ref, mask in (("all others", ~is_nino), ("neutral only", (group == "neutral").to_numpy())):
sel = is_nino | mask
diff, p = onset.median_difference_permutation(a.to_numpy()[sel], is_nino[sel], n=10_000, seed=0)
_, p2 = onset.median_difference_permutation(a.to_numpy()[sel], is_nino[sel], n=10_000, seed=1)
rows.append({"rule": rule, "El Nino vs": ref, "median difference (days)": round(diff, 1), "p": round(p, 4),
"p, other seed": round(p2, 4)}) # p is never 0: the smallest possible is 1 / 10,001
TESTS = pd.DataFrame(rows)
TESTS| rule | El Nino vs | median difference (days) | p | p, other seed | |
|---|---|---|---|---|---|
| 0 | BMKG rule | all others | 15.0 | 0.0142 | 0.0141 |
| 1 | BMKG rule | neutral only | 10.0 | 0.4530 | 0.4621 |
| 2 | cumulative 200 mm | all others | 19.5 | 0.0006 | 0.0003 |
| 3 | cumulative 200 mm | neutral only | 12.5 | 0.0058 | 0.0069 |
Look before moving on. Every season as one dot, by group and rule, with each group’s median as a bar. The test above compares the medians; the plot shows whether the El Nino seasons sit later as a group or whether one or two extreme seasons carry the difference. With 15 or so seasons per group, a single season can move a median by several days, so read the dots, not only the p-value.
fig, axes = plt.subplots(1, 2, figsize=(10, 3.4), sharey=True, constrained_layout=True)
order = ["La Nina", "neutral", "El Nino"]
for ax, (rule, a) in zip(axes, ANOM.items()):
for k, gname in enumerate(order):
v = a[group == gname]
ax.scatter(np.full(v.size, k) + np.linspace(-0.15, 0.15, v.size), v, s=14)
ax.hlines(v.median(), k - 0.3, k + 0.3, color="black", lw=1.5)
ax.axhline(0, color="grey", lw=0.6)
ax.set_xticks(range(3), [f"{g}\n(n={int((group == g).sum())})" for g in order])
ax.set_title(rule, fontsize=10)
axes[0].set_ylabel("NTT median onset anomaly (days)")
plt.show()
for rule, a in ANOM.items():
print(rule + ":", ", ".join(f"{g} median {a[group == g].median():+.0f} d" for g in order))
BMKG rule: La Nina median -10 d, neutral median +0 d, El Nino median +10 d
cumulative 200 mm: La Nina median -15 d, neutral median +0 d, El Nino median +12 d
Does the grouping matter? The main grouping asks whether October, the centre of September-November, lies inside an El Nino episode. The alternative counts a season as El Nino if any month from August to January lies inside one, which also admits episodes that begin between November and January, at or after the usual onset (the cell prints when each moved season’s episode starts). It is a worse test of cause, but a result that holds under both groupings is less likely to be an artefact of where the line was drawn. The cell repeats the BMKG-rule test with it.
def overlaps(s, eps):
a, b = pd.Timestamp(s, 8, 1), pd.Timestamp(s + 1, 1, 1)
return any((e["start"] <= b) & (e["end"] >= a) for _, e in eps.iterrows())
alt = np.array([overlaps(s, nino) for s in SEASONS])
moved = [f"{s}-{(s + 1) % 100:02d}" for s, x, y in zip(SEASONS, alt, is_nino) if x != y]
diff, p = onset.median_difference_permutation(ANOM["BMKG rule"].to_numpy(), alt, n=10_000, seed=0)
print(f"Aug-Jan grouping: {alt.sum()} El Nino seasons (moved: {', '.join(moved) or 'none'}); BMKG rule, El Nino vs all others: "
f"median difference {diff:+.1f} days, p {p:.3f}")
for s, x, y in zip(SEASONS, alt, is_nino):
if x != y:
e = next(e for _, e in nino.iterrows() if e["start"] <= pd.Timestamp(s + 1, 1, 1) and e["end"] >= pd.Timestamp(s, 8, 1))
print(f" {s}-{(s + 1) % 100:02d}: episode {e['label']} starts in the season centred on {e['start']:%B %Y}")Aug-Jan grouping: 17 El Nino seasons (moved: 1992-93, 2014-15); BMKG rule, El Nino vs all others: median difference +20.0 days, p 0.003
1992-93: episode 1993 starts in the season centred on January 1993
2014-15: episode 2014-16 starts in the season centred on November 2014
When tested, the 15 El Nino seasons started later than the 31 others by a median of 15 days with the BMKG rule (p = 0.014 with both seeds) and 19.5 days with the cumulative rule (p = 0.0006; 0.0003 with the second seed), and the BMKG result held with the August-January grouping (+20 days, p = 0.003). Against the 15 neutral seasons alone the difference shrank to 10 days with the BMKG rule (p about 0.45) and 12.5 days with the cumulative rule (p about 0.006). Part of the first contrast therefore comes from La Nina seasons, which started earlier (medians -10 and -15 days), not from El Nino alone. The BMKG differences are multiples of about 5 days, because a BMKG onset can only fall on the first day of a dasarian and a median over 30 baseline seasons can fall halfway between two of them.
So for this record: onset in El Nino seasons was later than in the other seasons, in line with what Naylor et al. state for Indonesia’s main rice-growing regions. Against neutral seasons only, the delay is about ten days; with the cumulative rule p is about 0.006, which stays below 0.05 even when multiplied by the five tests of this section (a Bonferroni correction), while with the BMKG rule the delay is not distinguishable from chance. Three limits stay: 15 El Nino seasons is a small sample; the dates are AgERA5 dates, a reanalysis product, not rain-gauge dates (section 1); and BMKG’s rule is applied per cell rather than per season zone. A test like this can support or fail to support a published claim for this data; it cannot show a mechanism.
9. Checkpoint
The cell checks what the chapter built: the datasets and their counts, that the GRASS and numpy versions agreed wherever both exist, and that every onset lies inside its season. It uses results from every section, so after a kernel restart run sections 2 to 8 first (finished GRASS steps are skipped).
t0 = time.time()
assert tgis.n_maps("precip") == sum(len(days_of(y)) for y in GRASS_YEARS), "re-run section 2"
assert tgis.n_maps("precip_das") == len(onset.dasarian_intervals(GRASS_YEARS[0], GRASS_YEARS[-1])), "re-run section 3"
assert worst < 0.01 and same_nulls, "GRASS and numpy dasarian totals differ"
assert len(acc_rows) == n_days, "re-run section 5"
assert tgis.n_maps("precip_occ") == tgis.n_maps("precip_ind") > 0, "re-run section 6"
assert tgis.n_maps("season") == len(TEACH_SEASONS) == tgis.n_maps("onset_cum"), "re-run section 6"
for r in on_rows:
g, n = preview.read(r["name"]), CUM_DAY[SEASONS.index(int(r["start_time"][:4]))].astype(float)
n[n < 0] = np.nan
assert np.all(((g == n) | (np.isnan(g) & np.isnan(n)))[land]), f"{r['name']} differs from numpy"
assert agree == land.sum(), "r.mapcalc BMKG onset differs from numpy"
for arr in (DAY_B, CUM_DAY):
v = arr[:, NTT]
assert v.max() < 366 and v.min() >= -1, "onset outside the season"
assert set(group) <= {"El Nino", "La Nina", "neutral"} and len(group) == len(SEASONS)
n_files, mb = tgis.folder_stats(PROJECT / HERE)
print(f"All checks passed. 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. Mapset ch07: 37,272 files, 19 MB | checkpoint 34 s | chapter run time 1036 s
Summary
What now exists:
- Mapset
ch07: daily precipitationprecip_YYYYMMDDforGRASS_YEARSin datasetprecip; the dasarian samplerdasarianand the totalsprecip_das; the running totalsprecip_acc, the occurrence and indicator datasetsprecip_occandprecip_ind, the season samplerseasonand the onset mapsonset_cumfor the teaching seasons;onset_bmkg_<season>from ther.mapcalccheck. - In
paths.staged: one precipitation file per year, 1979-2025, for the area. - In
src/pgca:onset.py(dasarian, the two rules, dry spells, the permutation test), with tests intests/test_onset.py.
What you can now do: build calendar periods GRASS has no granularity for, accumulate and detect thresholds with the temporal framework and check the result, turn an agency rule into code and say where it was adapted, and test a published claim with the right unit of evidence.
This is the last chapter of the series. The same pattern, a rule written as code, checked in GRASS and numpy, and tested against the record with the season as the unit, carries over to other onsets and indices.
Left out on purpose. A water balance (rain minus the ETrs of Chapter 4) would accumulate the same way, since method="mean" keeps negative values, but its natural onset is the date the running balance stops falling, a minimum that t.rast.accdetect cannot find. It would need its own rule.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
TypeError: The Parameter <limits> require multiple inputs |
pygrass wants limits (and range) as a tuple |
limits=(0, 1), not "0,1" |
t.rast.accumulate or t.rast.accdetect seems to hang, silently |
a cycle with no maps in the input: the 8.5 scripts then never move to the next cycle (ledger C110, from the source; not seen in a run) | keep start/stop inside the precip dataset; section 5 asserts it |
g.copy says “Unable to copy”, or r.mapcalc stops with exit code 3221226505 |
the map was made by g.copy and is a read-only file on this Windows build (ledger C111); t.rast.aggregate.ds also uses g.copy when an interval holds exactly one input map |
make such maps with r.mapcalc; to start again, delete the chapter’s mapset folder |
ValueError: ... is not in list in section 3 or 4 |
the numpy record does not cover the season | run section 2 again; seasons end in July 2025 |
AssertionError: re-run section 2 |
an interrupted import | run section 2 again; finished years are skipped |
| Onset maps empty for some cells | no onset that season by that rule | expected in dry seasons; counted in sections 4 and 6 |
References
- BMKG Stasiun Klimatologi Bali (2025). Buletin Prediksi Musim Hujan 2025-2026 Provinsi Bali. https://staklim-bali.bmkg.go.id/wp-content/uploads/2025/10/pmh-2025-2026_compressed.pdf
- BMKG Stasiun Klimatologi Sumatera Selatan (2025). Buletin Prediksi Musim Hujan 2025/2026. https://staklim-sumsel.bmkg.go.id/wp-content/uploads/2023/09/Buletin-PMH-2025-2026.pdf
- Dinas Pertanian dan Ketahanan Pangan Provinsi NTT (2026). BMKG Prediksi Curah Hujan NTT Meningkat Bertahap hingga Desember 2026 (23 September 2026; reports the BMKG NTT climatology bulletin of September 2026 and BMKG’s onset outlook of 22 September 2026). https://distankp.nttprov.go.id/prediksi-curah-hujan-ntt-oktober-desember-2026/
- Giarno, Dupe, Z. L. and Mustofa, M. A. (2012). Kajian awal musim hujan dan awal musim kemarau di Indonesia. Jurnal Meteorologi dan Geofisika 13(1). https://dx.doi.org/10.31172/jmg.v13i1.113
- Naylor, R. L., Battisti, D. S., Vimont, D. J., Falcon, W. P. and Burke, M. B. (2007). Assessing risks of climate variability and climate change for Indonesian rice agriculture. PNAS 104(19), 7752-7757. https://doi.org/10.1073/pnas.0701825104
- Lavers, D. A., Simmons, A., Vamborg, F. and Rodwell, M. J. (2022). An evaluation of ERA5 precipitation for climate monitoring. Quarterly Journal of the Royal Meteorological Society 148, 3152-3165. https://doi.org/10.1002/qj.4351
- NOAA Climate Prediction Center. Relative Oceanic Nino Index: https://www.cpc.ncep.noaa.gov/products/analysis_monitoring/enso/roni/
- GRASS Development Team. Manual pages: t.rast.accumulate, t.rast.accdetect, r.series.accumulate, t.rast.aggregate.ds, t.rast.aggregate, r.mapcalc