You will build: idx.season_index (rain, 1991-2020 normal, deficit below normal and its rank against 1991-2020, per insured unit, season, crop year 1981-2025 and stage, with the equal-weight season index)
You need: Chapter 7
Time to run: Under a minute (the checkpoint prints the time)
Level: Intermediate
The crop calendar of Chapter 7 says which dekads belong to each season and stage. This chapter turns the rain of those dekads into one number per unit, season and crop year: a drought index. It compares each dekad with its normal, the mean rain of the same dekad of the season over 1991-2020, and adds up the millimetres missing in each stage. Each stage’s deficit is then ranked against the same 30 reference years, so that a stage rank of 0.9 means “a larger deficit than in 27 of the 30 reference seasons” in every unit, wet or dry; the index is the mean of the three stage ranks. On the way the chapter shows why the reference must be fixed: ranks taken against the whole record change the past every time a year is added. Like all parameters of this series, the index is illustrative, not part of a priced insurance product.
NoteLearning objectives
By the end of this chapter you will be able to:
compute a normal over a reference period alongside every row with avg() FILTER (WHERE ...) OVER (...);
sum a one-sided deficit with greatest() and add stage and season totals with UNION ALL;
show that percent_rank() as a window function over a growing record moves past values;
rank values against a fixed reference set with the hypothetical-set aggregate percent_rank(x) WITHIN GROUP;
add computed columns to an existing table with ALTER TABLE and UPDATE ... FROM, and check the result in pandas.
Before running this chapter:
complete Chapter 7, which builds the calendar idx.season_dekad used here, and the chapters before it;
allow under a minute for the whole chapter. No downloads are needed. A step whose table or column already exists is skipped on a second run.
1. Setup
The setup cell reads config.yml, defines connect() and ENGINE as in the earlier chapters, and checks the tables of Chapters 5 to 7. Four settings are the chapter’s own:
REF, the reference period 1991-2020 for normals and ranks, the standard climatological period that WMO recommends (ledger L78), and the period Chapter 7 took its medians from;
FIRST_YEAR, the first crop year of the index: 1981, the first whose two seasons lie wholly in the record in every unit (Chapter 7);
UNIT and DRY_YEAR, the unit and the crop year looked at closely: Garut, as before, and crop year 2018, whose MK1 grew in the dry season of 2019. In the damage record of 2016-2025, 66 of the 230 MK1 drought events (a unit reporting drought damage, terkena, on more than 1% of its paddy in April-September) fell in 2019 (ledger L62).
The cell also finds the last crop year in which every unit has both seasons complete, and stops if REF does not lie inside the crop years of the index.
import osos.environ.setdefault("MKL_THREADING_LAYER", "SEQUENTIAL") # before numpy is imported (ledger L128)import datetime as dtimport timefrom pathlib import Pathimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport psycopgimport yamlfrom psycopg import sqlfrom sqlalchemy import URL, create_engineT0 = time.perf_counter()REF = {"ref_first": 1991, "ref_last": 2020} # reference period of normals and ranksFIRST_YEAR =1981# first crop year of the indexUNIT ="3205"# BPS code of Kabupaten GarutDRY_YEAR =2018# crop year looked at closely (MK1 in 2019)ROOT = Path.cwd() if (Path.cwd() /"tutorial.yml").exists() else Path.cwd().parentCONFIG = yaml.safe_load((ROOT /"config.yml").read_text(encoding="utf-8"))DB = CONFIG["database"]defconnect(**kwargs):"""A new session in the tutorial database (Chapter 2)."""return psycopg.connect(**DB, **kwargs)ENGINE = create_engine(URL.create("postgresql+psycopg", username=DB["user"], host=DB["host"], port=DB["port"], database=DB["dbname"]))withconnect() as conn:print("connected |", conn.execute("SELECT postgis_full_version()").fetchone()[0][:60], "...")for table in ["idx.insured_unit", "idx.dekad_rain", "idx.crop_calendar", "idx.season_dekad", "idx.data_status"]:ifnot conn.execute("SELECT to_regclass(%s)", [table]).fetchone()[0]:raiseRuntimeError(f"{table} is missing: run Chapters 3 to 7 first") found = conn.execute("SELECT name FROM idx.insured_unit WHERE code = %s", [UNIT]).fetchone()if found isNone:raiseValueError(f"UNIT {UNIT} is not an insured unit: pick a code from idx.insured_unit") unit_name = found[0]# the last crop year in which every unit and season is complete (Chapter 7 keeps complete seasons only) last_year = conn.execute("""SELECT min(y) FROM (SELECT max(crop_year) AS y FROM idx.season_dekad GROUP BY kabupaten_code, season) s""").fetchone()[0]ifnot FIRST_YEAR <= REF["ref_first"] <= REF["ref_last"] <= last_year:raiseValueError(f"REF {REF} must lie within the crop years {FIRST_YEAR}-{last_year}")N_REF = REF["ref_last"] - REF["ref_first"] +1print(f"unit: {UNIT}{unit_name} | index crop years {FIRST_YEAR}-{last_year} | "f"reference {REF['ref_first']}-{REF['ref_last']} ({N_REF} years)")
The index of this series is the deficit below normal: for each dekad of a stage, how many millimetres the rain fell short of that dekad’s normal, added up over the stage. A dekad wetter than normal counts as 0, not as a credit, so a wet dekad cannot cancel a dry one in the same stage. A deficit can never exceed the normal, which it reaches when no rain falls at all.
Several candidates were compared before this one was chosen (ledger L61 to L63): the deficit-type indices (season rain, the deficit below a fixed 50 mm, a simple water balance) rank the MK1 seasons almost alike, while counts of dry dekads rank them less alike; against the reported drought damage none did better than plain season rain, and the water balance did worse; weighting the reproductive stage double gained nothing. The series keeps the deficit below normal because it reads plainly, as millimetres below normal, and because building it shows the SQL of this chapter. It uses the rain over all paddy (regime all), since rain over irrigated or rainfed paddy ranks the seasons almost the same (ledger L62).
One caveat belongs here. In 92 of the 99 units the median MK1 season of 1991-2020 brings less than 450 mm of rain (ledger L60), the lower end of FAO’s indicative, rough estimate of 450 to 700 mm as the water need of a rice crop (ledger L65). In irrigated paddy the difference comes from irrigation; rainfed paddy has no such supply. The index measures how much less rain fell than usual, which is not the same as the water stress of the crop.
3. Normals with a window function
The normal of a dekad is the mean rain of that unit, season and dekad of the season (1 to 10) over the reference crop years. As a window function, avg(mm) FILTER (WHERE crop_year BETWEEN ...) OVER (PARTITION BY kabupaten_code, season, dekad_no) computes it next to every row:
the window holds all crop years of the same unit, season and dekad; with no ORDER BY inside OVER, the mean covers the whole window (with one, it would become a running mean);
the FILTER lets only the reference years into the mean. Only window functions that are also aggregates, such as avg and sum, accept FILTER; window-only functions such as lead and percent_rank do not (ledger L67).
The query shows it for UNIT, the MK1 season of DRY_YEAR.
NORMAL_DEMO ="""WITH d AS ( SELECT s.crop_year, s.dekad_no, s.stage, s.dekad_start, r.mm, avg(r.mm) FILTER (WHERE s.crop_year BETWEEN %(ref_first)s AND %(ref_last)s) OVER (PARTITION BY s.dekad_no) AS normal_mm FROM idx.season_dekad s JOIN idx.dekad_rain r ON r.kabupaten_code = s.kabupaten_code AND r.dekad_start = s.dekad_start AND r.regime = 'all' WHERE s.kabupaten_code = %(u)s AND s.season = 'MK1' AND s.crop_year >= %(first)s)SELECT dekad_no, stage, dekad_start, round(mm::numeric, 1) AS mm, round(normal_mm::numeric, 1) AS normal_mm, round(greatest(normal_mm - mm, 0)::numeric, 1) AS below_normalFROM d WHERE crop_year = %(y)s ORDER BY dekad_no"""demo = pd.read_sql(NORMAL_DEMO, ENGINE, params={**REF, "u": UNIT, "first": FIRST_YEAR, "y": DRY_YEAR})print(f"{unit_name}, MK1 of crop year {DRY_YEAR}: rain {demo.mm.sum():.0f} mm, normal {demo.normal_mm.sum():.0f} mm, "f"deficit {demo.below_normal.sum():.0f} mm")print(demo.groupby("stage", sort=False)[["mm", "normal_mm", "below_normal"]].sum().round(0))demo
Garut, MK1 of crop year 2018: rain 91 mm, normal 362 mm, deficit 271 mm
mm normal_mm below_normal
stage
vegetative 33.0 185.0 152.0
reproductive 21.0 96.0 75.0
ripening 37.0 81.0 44.0
dekad_no
stage
dekad_start
mm
normal_mm
below_normal
0
1
vegetative
2019-05-21
2.4
65.6
63.2
1
2
vegetative
2019-06-01
29.2
48.8
19.6
2
3
vegetative
2019-06-11
0.1
42.7
42.6
3
4
vegetative
2019-06-21
1.4
27.7
26.3
4
5
reproductive
2019-07-01
5.7
26.1
20.4
5
6
reproductive
2019-07-11
2.6
36.9
34.3
6
7
reproductive
2019-07-21
12.3
32.8
20.5
7
8
ripening
2019-08-01
9.3
23.3
14.0
8
9
ripening
2019-08-11
15.0
25.8
10.9
9
10
ripening
2019-08-21
12.8
32.0
19.2
Here the query keeps one unit and one season, so the window is partitioned by dekad_no alone. The WHERE crop_year = DRY_YEAR is applied in the outer query, after the window function: inside the CTE all crop years from 1981 are present, so the normal is the mean of the 30 reference years even though only one year is shown.
Look before moving on. Each below_normal is normal_mm - mm where that is positive and 0 where the dekad was wetter than normal. In this season every dekad fell short, so the deficit equals the normal minus the rain; with one wetter dekad the deficit would be larger than that difference. The stage totals printed above the table come back in section 6. The figure shows the same season against its normal.
fig, ax = plt.subplots(figsize=(8, 3.2))x = demo.dekad_no.to_numpy()ax.bar(x -0.2, demo.normal_mm.astype(float), width=0.4, color="0.7", label="normal 1991-2020")ax.bar(x +0.2, demo.mm.astype(float), width=0.4, color="tab:blue", label=f"crop year {DRY_YEAR}")for boundary in demo.dekad_no[demo.stage != demo.stage.shift()].iloc[1:] -0.5: # where the stage changes ax.axvline(boundary, color="0.4", linewidth=0.6, linestyle=":")ax.set_xticks(x); ax.set_xlabel("dekad of the MK1 season (stages split at the dotted lines)")ax.set_ylabel("mm"); ax.set_title(f"{unit_name}: MK1 rain against its normal"); ax.legend()plt.show()
4. Rain, normal and deficit for every unit, season, crop year and stage
The table idx.season_index starts with the rain, normal and deficit; the ranks come in sections 5 and 6. The query computes the normals for all units at once (the window is partitioned by unit, season and dekad), then groups the dekads twice: by stage, and over the whole season with the stage name 'season'. UNION ALL stacks the two, so each unit, season and crop year has four rows. The constraints added after the build state the rules of the columns: no missing values, and a deficit between 0 and the normal. The table comment records the settings it was built with. The build takes about a second.
SEASON_INDEX ="""CREATE TABLE idx.season_index ASWITH d AS ( SELECT s.kabupaten_code, s.season, s.crop_year, s.stage, s.dekad_no, r.mm, avg(r.mm) FILTER (WHERE s.crop_year BETWEEN %(ref_first)s AND %(ref_last)s) OVER (PARTITION BY s.kabupaten_code, s.season, s.dekad_no) AS normal_mm FROM idx.season_dekad s JOIN idx.dekad_rain r ON r.kabupaten_code = s.kabupaten_code AND r.dekad_start = s.dekad_start AND r.regime = 'all' WHERE s.crop_year BETWEEN %(first)s AND %(last)s)SELECT kabupaten_code, season, crop_year, stage, sum(mm) AS rain_mm, sum(normal_mm) AS normal_mm, sum(greatest(normal_mm - mm, 0)) AS deficit_mmFROM dGROUP BY kabupaten_code, season, crop_year, stageUNION ALLSELECT kabupaten_code, season, crop_year, 'season', sum(mm), sum(normal_mm), sum(greatest(normal_mm - mm, 0))FROM dGROUP BY kabupaten_code, season, crop_year"""withconnect() as conn:if conn.execute("SELECT to_regclass('idx.season_index')").fetchone()[0]:print("idx.season_index already exists: left as it is |", conn.execute("SELECT obj_description('idx.season_index'::regclass)").fetchone()[0])else: t = time.perf_counter() conn.execute(SEASON_INDEX, {**REF, "first": FIRST_YEAR, "last": last_year}) conn.execute("""ALTER TABLE idx.season_index ADD PRIMARY KEY (kabupaten_code, season, crop_year, stage), ADD FOREIGN KEY (kabupaten_code, season) REFERENCES idx.crop_calendar (kabupaten_code, season), ALTER COLUMN rain_mm SET NOT NULL, ALTER COLUMN normal_mm SET NOT NULL, ALTER COLUMN deficit_mm SET NOT NULL, ADD CHECK (stage IN ('vegetative', 'reproductive', 'ripening', 'season')), ADD CHECK (deficit_mm >= 0 AND deficit_mm <= normal_mm + 1e-9)""") conn.execute(sql.SQL("COMMENT ON TABLE idx.season_index IS {}").format(sql.Literal(f"Drought index, crop years {FIRST_YEAR}-{last_year}, reference {REF['ref_first']}-{REF['ref_last']}: rain, normal ""and deficit below normal (mm) per insured unit, season, crop year and stage ('season' = whole season); ""deficit_prank = percent_rank(x) WITHIN GROUP of the deficit against the reference years of the same unit, ""season and stage; stage_mean_prank = equal-weight mean of the three stage ranks (season rows); "f"built {dt.date.today()} by Chapter 8"))) conn.execute("ANALYZE idx.season_index")print(f"idx.season_index (rain, normal, deficit) built in {time.perf_counter() - t:.1f} s") summary = pd.DataFrame(conn.execute(""" SELECT season, stage, count(*), round(avg(normal_mm)::numeric, 1), round(avg(deficit_mm)::numeric, 1), round(100.0 * avg((deficit_mm = 0)::int), 1) FROM idx.season_index GROUP BY season, stage ORDER BY season, array_position(ARRAY['vegetative', 'reproductive', 'ripening', 'season'], stage)""").fetchall(), columns=["season", "stage", "rows", "mean_normal_mm", "mean_deficit_mm", "zero_deficit_pct"])summary
idx.season_index (rain, normal, deficit) built in 1.5 s
season
stage
rows
mean_normal_mm
mean_deficit_mm
zero_deficit_pct
0
MH
vegetative
4455
433.6
80.8
7.7
1
MH
reproductive
4455
366.5
58.1
15.3
2
MH
ripening
4455
335.9
55.0
11.5
3
MH
season
4455
1136.0
194.0
0.1
4
MK1
vegetative
4455
197.3
62.5
8.4
5
MK1
reproductive
4455
92.0
42.8
13.1
6
MK1
ripening
4455
67.8
29.4
10.6
7
MK1
season
4455
357.1
134.7
2.1
array_position(ARRAY[...], stage) orders the stages by their place in the array rather than by alphabet.
Look before moving on. Each season and stage should have 99 x 45 = 4,455 rows (units times crop years 1981-2025). MH has a far larger normal than MK1, and so a larger deficit in millimetres; that is why the index works with ranks, which put a wet and a dry season, or unit, on the same scale. A whole season rarely has no deficit at all, but a single stage has none in about one season in ten (zero_deficit_pct); section 5 shows what that does to the ranks.
5. Ranking without moving the past
A deficit of 150 mm means little on its own: it is a severe shortfall where the normal is 200 mm and a small one where it is 1,000 mm. The series ranks each deficit among the deficits of the same unit, season and stage. The obvious tool is the window function percent_rank() OVER (PARTITION BY ... ORDER BY deficit_mm). It returns (rank - 1) / (n - 1), where rank is the row’s place in the order (tied rows share the lowest place) and n the number of rows in the partition. The partition is the whole record, and the record grows: when a crop year is added, n grows by one and every rank can shift. The cell ranks the season deficits twice, once with the record ending in the last crop year and once with it ending a year earlier, and counts how many of the common past crop years get a different rank.
DRIFT ="""WITH upto_last AS ( SELECT kabupaten_code, season, crop_year, percent_rank() OVER (PARTITION BY kabupaten_code, season ORDER BY deficit_mm) AS r FROM idx.season_index WHERE stage = 'season' AND crop_year <= %(last)s),upto_before AS ( SELECT kabupaten_code, season, crop_year, percent_rank() OVER (PARTITION BY kabupaten_code, season ORDER BY deficit_mm) AS r FROM idx.season_index WHERE stage = 'season' AND crop_year <= %(last)s - 1)SELECT a.season, count(*) AS past_seasons, count(*) FILTER (WHERE a.r <> b.r) AS rank_changed, round(max(abs(a.r - b.r))::numeric, 3) AS largest_changeFROM upto_last a JOIN upto_before b USING (kabupaten_code, season, crop_year)GROUP BY a.season ORDER BY a.season"""pd.read_sql(DRIFT, ENGINE, params={"last": last_year})
season
past_seasons
rank_changed
largest_change
0
MH
4356
4159
0.023
1
MK1
4356
4118
0.022
Look before moving on. Most past seasons change rank when one year is added, because every rank is a share of a total that just grew. The changes look small, but a payout that starts at a threshold turns a small change into a payment or none: in the review of this design, adding one crop year changed the payout of hundreds of past unit-seasons (ledger L73).
The fix is to rank against a fixed set: the deficits of the 30 reference years. PostgreSQL has a form of percent_rank for exactly this, a hypothetical-set aggregate, written with the same WITHIN GROUP (ORDER BY ...) as percentile_disc in Chapter 7: percent_rank(x) WITHIN GROUP (ORDER BY v) returns the rank that x would have if it were added to the values v. For a deficit x and the 30 reference deficits, it is (number of reference deficits below x) / 30:
0 for a deficit no larger than the smallest reference deficit, which includes every stage without a deficit;
at most 29/30 within the reference years (the largest reference deficit has 29 below it);
1 only for a season outside 1991-2020 with a deficit larger than all 30.
Adding a year to the record adds a row but changes no rank, since the reference set stays the same (ledger L80).
A hypothetical-set aggregate cannot be used as a window function (ledger L78), so each row is joined to the 30 reference rows of its unit, season and stage, and the aggregate runs once per group. The x of percent_rank(x) must have one value per group, which is why a.deficit_mm is in the GROUP BY.
The cell adds a column deficit_prank to the table and fills it with UPDATE ... FROM, which updates each row from the matching row of a subquery; (t.a, t.b, ...) = (r.a, r.b, ...) compares the four key columns at once, like four equalities joined by AND. The order is: add the column, fill it, then forbid empty values and values outside 0 to 1. On the season rows, deficit_prank ranks the season’s total deficit; it is kept for comparison, and the index is the column of section 6.
RANKS ="""UPDATE idx.season_index tSET deficit_prank = r.deficit_prankFROM ( SELECT a.kabupaten_code, a.season, a.crop_year, a.stage, percent_rank(a.deficit_mm) WITHIN GROUP (ORDER BY f.deficit_mm) AS deficit_prank FROM idx.season_index a JOIN idx.season_index f ON f.kabupaten_code = a.kabupaten_code AND f.season = a.season AND f.stage = a.stage AND f.crop_year BETWEEN %(ref_first)s AND %(ref_last)s GROUP BY a.kabupaten_code, a.season, a.crop_year, a.stage, a.deficit_mm) rWHERE (t.kabupaten_code, t.season, t.crop_year, t.stage) = (r.kabupaten_code, r.season, r.crop_year, r.stage)"""def has_column(conn, column: str) ->bool:return conn.execute("""SELECT 1 FROM information_schema.columns WHERE table_schema = 'idx' AND table_name = 'season_index' AND column_name = %s""", [column]).fetchone() isnotNonewithconnect() as conn:if has_column(conn, "deficit_prank"):print("deficit_prank already exists: left as it is")else: t = time.perf_counter() conn.execute("ALTER TABLE idx.season_index ADD COLUMN deficit_prank double precision") n = conn.execute(RANKS, REF).rowcount conn.execute("ALTER TABLE idx.season_index ALTER COLUMN deficit_prank SET NOT NULL, ""ADD CHECK (deficit_prank BETWEEN 0 AND 1)")print(f"deficit_prank set on {n:,} rows in {time.perf_counter() - t:.1f} s") check = conn.execute("""SELECT min(deficit_prank), max(deficit_prank), max(deficit_prank) FILTER (WHERE crop_year BETWEEN %(ref_first)s AND %(ref_last)s), round(100.0 * avg((deficit_prank = 0)::int) FILTER (WHERE stage <> 'season' AND crop_year BETWEEN %(ref_first)s AND %(ref_last)s), 1) FROM idx.season_index""", REF).fetchone() at_one = pd.DataFrame(conn.execute("""SELECT crop_year, count(*) FROM idx.season_index WHERE deficit_prank = 1 GROUP BY crop_year ORDER BY 2 DESC LIMIT 6""").fetchall(), columns=["crop_year", "rows_at_1"])print(f"deficit_prank from {check[0]} to {check[1]}; within the reference years at most {check[2]:.4f} "f"(29/30 = {29/30:.4f}); reference stage ranks at exactly 0: {check[3]}%")print("crop years with the most rows at 1:", dict(zip(at_one.crop_year, at_one.rows_at_1)))
deficit_prank set on 35,640 rows in 1.2 s
deficit_prank from 0.0 to 1.0; within the reference years at most 0.9667 (29/30 = 0.9667); reference stage ranks at exactly 0: 10.7%
crop years with the most rows at 1: {1990: 47, 1982: 46, 1986: 26, 2025: 21, 1981: 16, 1984: 11}
Look before moving on. No rank should be below 0 or above 1, and no reference year should reach 1. The rows at 1 should all fall outside 1991-2020. Note the share of reference stage ranks at exactly 0: every stage without a deficit shares rank 0, so the ranks are not spread evenly from 0 to 29/30 but pile up at 0 and are close to even above it. Stages with no rain at all tie too, at the top, since their deficit equals the normal.
6. The equal-weight index
The index of a season is the mean of its three stage ranks. It goes on the 'season' rows, in a column stage_mean_prank; on the stage rows it stays NULL. The query uses the same window pattern as section 3: avg(deficit_prank) FILTER (WHERE stage <> 'season') OVER (PARTITION BY kabupaten_code, season, crop_year) takes the mean of the three stage rows next to every row of the same season, and the UPDATE keeps it on the season row.
The mean is rounded to 12 decimals. The ranks are fractions k/30 stored as binary floating-point numbers, which cannot hold most of them exactly, and the mean of three such numbers can land one step (about 2e-16) away from the number nearest its exact value. Two seasons with the same true index could then differ in the last bit, and at a trigger that difference would decide whether a season pays: before the rounding, 11 unit-seasons of the back-test paid less than a billionth of the sum insured for that reason alone (ledger L166). Rounding gives every equal mean the same value.
STAGE_MEAN ="""UPDATE idx.season_index tSET stage_mean_prank = m.stage_mean_prankFROM ( SELECT kabupaten_code, season, crop_year, stage, round((avg(deficit_prank) FILTER (WHERE stage <> 'season') OVER (PARTITION BY kabupaten_code, season, crop_year))::numeric, 12)::double precision AS stage_mean_prank FROM idx.season_index) mWHERE (t.kabupaten_code, t.season, t.crop_year, t.stage) = (m.kabupaten_code, m.season, m.crop_year, m.stage) AND t.stage = 'season'"""withconnect() as conn:if has_column(conn, "stage_mean_prank"):print("stage_mean_prank already exists: left as it is")else: t = time.perf_counter() conn.execute("ALTER TABLE idx.season_index ADD COLUMN stage_mean_prank double precision") n = conn.execute(STAGE_MEAN).rowcount conn.execute("ALTER TABLE idx.season_index ADD CHECK ((stage = 'season') = (stage_mean_prank IS NOT NULL))") conn.execute("ANALYZE idx.season_index")print(f"stage_mean_prank set on {n:,} season rows in {time.perf_counter() - t:.1f} s")index = pd.read_sql("""SELECT kabupaten_code, season, crop_year, stage_mean_prank FROM idx.season_index WHERE stage = 'season'""", ENGINE)ref = index[index.crop_year.between(REF["ref_first"], REF["ref_last"])]print(ref.groupby("season").stage_mean_prank.describe(percentiles=[0.5, 0.8, 0.95]).round(3))
stage_mean_prank set on 8,910 season rows in 0.4 s
count mean std min 50% 80% 95% max
season
MH 2970.0 0.477 0.187 0.0 0.478 0.644 0.800 0.956
MK1 2970.0 0.479 0.237 0.0 0.478 0.722 0.839 0.956
The CHECK added at the end states the rule of the column in the table itself: a value on every season row and on no stage row.
Look before moving on. The mean of three ranks gathers towards the middle, since a season is rarely the driest in all three stages at once. Compare the 80th and 95th percentiles above with 0.8 and 0.95: in the reference years an index of 0.8 is reached far less often than one season in five. A threshold such as “the index above 0.8” would therefore not mean a 1-in-5 drought; Chapter 9 takes its trigger and exit (Chapter 1, section 2) as percentiles of the index itself.
The figure shows the index of UNIT over the record, for both seasons, and the table lists its five driest MK1 seasons. Seasons that end after the date to which the rainfall is final are marked provisional: their rain can still change in a later release of CHIRPS (idx.data_status, Chapter 4).
u = index[index.kabupaten_code == UNIT].sort_values("crop_year")fig, ax = plt.subplots(figsize=(9, 3.2))ax.axvspan(REF["ref_first"] -0.5, REF["ref_last"] +0.5, color="0.92", label="reference 1991-2020")for season, g in u.groupby("season"): ax.plot(g.crop_year, g.stage_mean_prank, marker=".", label=season)ax.set_ylim(0, 1); ax.set_xlabel("crop year"); ax.set_ylabel("index (mean of stage ranks)")ax.set_title(f"{unit_name}: drought index, higher is drier"); ax.legend(fontsize=8)plt.show()top = pd.read_sql(""" SELECT i.crop_year, i.stage_mean_prank AS mk1_index, (SELECT stage_mean_prank FROM idx.season_index m WHERE m.kabupaten_code = i.kabupaten_code AND m.season = 'MH' AND m.crop_year = i.crop_year AND m.stage = 'season') AS mh_index, (SELECT max(s.dekad_start) FROM idx.season_dekad s WHERE s.kabupaten_code = i.kabupaten_code AND s.season = 'MK1' AND s.crop_year = i.crop_year) > (SELECT final_through FROM idx.data_status WHERE source = 'chirps_rnl') AS provisional FROM idx.season_index i WHERE i.kabupaten_code = %(u)s AND i.season = 'MK1' AND i.stage = 'season' ORDER BY i.stage_mean_prank DESC, i.crop_year LIMIT 5""", ENGINE, params={"u": UNIT})stage_ranks = pd.read_sql("""SELECT stage, round(deficit_mm::numeric) AS deficit_mm, round(normal_mm::numeric) AS normal_mm, round(deficit_prank::numeric, 3) AS deficit_prank FROM idx.season_index WHERE kabupaten_code = %(u)s AND season = 'MK1' AND crop_year = %(y)s ORDER BY array_position(ARRAY['vegetative', 'reproductive', 'ripening', 'season'], stage)""", ENGINE, params={"u": UNIT, "y": DRY_YEAR})print(top.round(3).to_string(index=False))print(f"\nMK1 of crop year {DRY_YEAR} by stage:")stage_ranks
Look before moving on. The five driest MK1 seasons of UNIT mix years from inside and outside the reference period, and a crop year can be dry in one season and not in the other (compare the two index columns). A season marked provisional rests on rainfall that can still change; Chapter 10 keeps such seasons apart from the final record.
DRY_YEAR is not at the top, although every dekad of its MK1 fell short (section 3). The table under the list shows why: its vegetative and reproductive stages rank high, but its ripening stage less so, and the index averages the three ranks with equal weights. A season extreme in two stages and moderate in the third does not top the list; the season’s total deficit (deficit_prank on the season row) ranks it higher.
7. Check against pandas
The cell recomputes the whole index of UNIT in pandas from idx.season_dekad and idx.dekad_rain, by the definitions of sections 3 to 6, without window functions or percent_rank, and compares every row with the table. It stops with an error if any row differs, including a value present on one side and missing on the other.
raw = pd.read_sql(""" SELECT s.season, s.crop_year, s.stage, s.dekad_no, r.mm FROM idx.season_dekad s JOIN idx.dekad_rain r ON r.kabupaten_code = s.kabupaten_code AND r.dekad_start = s.dekad_start AND r.regime = 'all' WHERE s.kabupaten_code = %(u)s AND s.crop_year BETWEEN %(first)s AND %(last)s""", ENGINE, params={"u": UNIT, "first": FIRST_YEAR, "last": last_year})in_ref = raw.crop_year.between(REF["ref_first"], REF["ref_last"])normal = raw[in_ref].groupby(["season", "dekad_no"]).mm.mean().rename("normal")raw = raw.join(normal, on=["season", "dekad_no"])raw["below"] = (raw.normal - raw.mm).clip(lower=0)per_stage = raw.groupby(["season", "crop_year", "stage"], as_index=False).below.sum()per_season = raw.groupby(["season", "crop_year"], as_index=False).below.sum().assign(stage="season")deficit = pd.concat([per_stage, per_season], ignore_index=True).rename(columns={"below": "deficit"})def rank_against_reference(group: pd.DataFrame) -> pd.Series:"""(number of reference deficits below each deficit) / (number of reference years).""" reference = group.loc[group.crop_year.between(REF["ref_first"], REF["ref_last"]), "deficit"].to_numpy()return group.deficit.apply(lambda x: (reference < x).sum() /len(reference))deficit["prank"] = deficit.groupby(["season", "stage"], group_keys=False)[["crop_year", "deficit"]].apply(rank_against_reference)stage_mean = deficit[deficit.stage !="season"].groupby(["season", "crop_year"]).prank.mean().rename("stage_mean")by_pandas = deficit.join(stage_mean, on=["season", "crop_year"])by_pandas.loc[by_pandas.stage !="season", "stage_mean"] = np.nandb = pd.read_sql("""SELECT season, crop_year, stage, deficit_mm, deficit_prank, stage_mean_prank FROM idx.season_index WHERE kabupaten_code = %(u)s""", ENGINE, params={"u": UNIT})both = db.merge(by_pandas, on=["season", "crop_year", "stage"], how="outer", indicator=True)assert (both._merge =="both").all(), "rows on one side only"assert np.allclose(both.deficit_mm, both.deficit, rtol=0, atol=1e-9), "deficits differ"assert (both.deficit_prank == both.prank).all(), "ranks differ"assert np.allclose(both.stage_mean_prank, both.stage_mean, rtol=0, atol=1e-12, equal_nan=True), "index differs"print(f"{len(both)} rows agree; largest differences: deficit {(both.deficit_mm - both.deficit).abs().max():.1e} mm, "f"rank {(both.deficit_prank - both.prank).abs().max():.1e}, "f"index {(both.stage_mean_prank - both.stage_mean).abs().max():.1e}")
360 rows agree; largest differences: deficit 1.7e-13 mm, rank 0.0e+00, index 4.4e-13
Look before moving on. The deficits agree to floating-point rounding and the ranks exactly: a rank is a count divided by 30, so a different rank would mean a different count, not rounding. The check uses the same join of calendar and rain as the table; the checkpoint below makes sure that join loses no dekad.
Checkpoint
The cell below checks, in a new session, what Chapter 9 relies on:
four rows per insured unit, season and crop year from 1981 on, each season built from all ten of its dekads;
30 reference years behind every rank;
stage rain and deficits that add up to the season’s;
ranks between 0 and 1, below 1 in every reference year;
the equal-weight index on every season row, equal to the mean of the three stage ranks, and on no stage row.
It depends only on the setup cell.
withconnect() as conn: first_row =lambda q, p=None: conn.execute(q, p).fetchone() n_units = first_row("SELECT count(*) FROM idx.insured_unit")[0] rows, units, y0, y1 = first_row("""SELECT count(*), count(DISTINCT kabupaten_code), min(crop_year), max(crop_year) FROM idx.season_index""") short_seasons = first_row("""SELECT count(*) FROM ( SELECT s.kabupaten_code, s.season, s.crop_year FROM idx.season_dekad s JOIN idx.dekad_rain r ON r.kabupaten_code = s.kabupaten_code AND r.dekad_start = s.dekad_start AND r.regime = 'all' WHERE s.crop_year BETWEEN %(first)s AND %(last)s GROUP BY 1, 2, 3 HAVING count(*) <> 10) x""", {"first": FIRST_YEAR, "last": last_year})[0] ref_groups = first_row("""SELECT count(*) FROM ( SELECT count(*) FILTER (WHERE crop_year BETWEEN %(ref_first)s AND %(ref_last)s) AS n FROM idx.season_index GROUP BY kabupaten_code, season, stage) g WHERE n <> %(n_ref)s""", {**REF, "n_ref": N_REF})[0] adds_up = first_row("""SELECT count(*) FROM ( SELECT sum(deficit_mm) FILTER (WHERE stage <> 'season') - max(deficit_mm) FILTER (WHERE stage = 'season') AS d, sum(rain_mm) FILTER (WHERE stage <> 'season') - max(rain_mm) FILTER (WHERE stage = 'season') AS r, count(*) AS n FROM idx.season_index GROUP BY kabupaten_code, season, crop_year) s WHERE abs(d) > 1e-6 OR abs(r) > 1e-6 OR n <> 4""")[0] ranks = first_row("""SELECT count(*) FILTER (WHERE deficit_prank IS NULL OR deficit_prank NOT BETWEEN 0 AND 1), count(*) FILTER (WHERE deficit_prank = 1 AND crop_year BETWEEN %(ref_first)s AND %(ref_last)s), count(*) FILTER (WHERE (stage = 'season') <> (stage_mean_prank IS NOT NULL)) FROM idx.season_index""", REF) index_off = first_row("""SELECT count(*) FROM idx.season_index s JOIN (SELECT kabupaten_code, season, crop_year, avg(deficit_prank) AS m FROM idx.season_index WHERE stage <> 'season' GROUP BY 1, 2, 3) a USING (kabupaten_code, season, crop_year) WHERE s.stage = 'season' AND abs(s.stage_mean_prank - a.m) > 1e-12""")[0]expected = n_units *2*4* (last_year - FIRST_YEAR +1)assert rows == expected and units == n_units and (y0, y1) == (FIRST_YEAR, last_year), \f"{rows} rows for {units} units, crop years {y0}-{y1}; expected {expected}"assert short_seasons ==0, f"{short_seasons} seasons with fewer than ten dekads of rain"assert ref_groups ==0, f"{ref_groups} unit-season-stage groups without {N_REF} reference years"assert adds_up ==0, f"{adds_up} seasons whose stages do not add up to the season"assert ranks == (0, 0, 0) and index_off ==0, f"ranks out of range, reference ranks at 1, misplaced index: {ranks}; index off: {index_off}"print(f"checkpoint passed: {rows:,} rows, {units} units x 2 seasons x crop years {y0}-{y1} x 4; "f"code cells took {time.perf_counter() - T0:.0f} s since the setup cell")
checkpoint passed: 35,640 rows, 99 units x 2 seasons x crop years 1981-2025 x 4; code cells took 6 s since the setup cell
Troubleshooting
Symptom
Cause
Fix
... is missing: run Chapters 3 to 7 first
an earlier chapter has not been run
run that chapter first
UNIT ... is not an insured unit
the setting in the setup cell changed
use a code from idx.insured_unit
REF ... must lie within the crop years ...
the reference period reaches outside the index
keep REF between FIRST_YEAR and the last crop year printed by the setup cell
you changed REF or FIRST_YEAR, but the outputs did not change
the table was built earlier with the old settings (its comment, printed in section 4, names them)
drop the tables of the later chapters first, then DROP TABLE idx.season_index, and run sections 4 to 6 again
column "deficit_prank" of relation "season_index" contains null values
the update of section 5 found no reference rows for some groups
check REF as above, DROP TABLE idx.season_index and run sections 4 to 6 again
idx.season_index already exists, but idx.season_dekad or idx.dekad_rain has changed
the cells never drop a table that later chapters use
drop the tables of the later chapters first, then DROP TABLE idx.season_index, and run sections 4 to 6 again (Chapter 7, Troubleshooting: no CASCADE)
Summary
You now have idx.season_index, with one row per insured unit, season, crop year from 1981 to the last complete one (2025, whose seasons are provisional), and stage (plus 'season' for the whole season):
rain_mm, normal_mm and deficit_mm: the rain, its 1991-2020 normal and the millimetres below normal;
deficit_prank: the rank of the deficit against the 30 reference years of the same unit, season and stage;
stage_mean_prank (season rows): the equal-weight drought index, higher is drier. This is the column Chapter 9 builds the contract on.
On the way you computed normals with a filtered window aggregate, saw a window rank move the past, and fixed it with a hypothetical-set aggregate against a fixed reference. The index is a ranking of rainfall shortfalls, illustrative and not a measure of crop loss: Chapter 11 compares it with reported damage.
What comes next
Chapter 9 turns the index into a contract: a trigger and an exit per unit from the index’s own 1991-2020 percentiles, and a payout that rises between them.