You will build: idx.crop_stage (three growth stages in dekads after transplanting), idx.crop_calendar (MH and MK1 transplanting dekad of each insured unit) and idx.season_dekad (every season of every crop year laid over the dekads of the record)
You need: Chapter 6
Time to run: Under a minute (the checkpoint prints the time)
Level: Intermediate
A drought index should measure rain while the crop is in the field: rain that falls after the harvest does not count for it. This chapter decides when rice grows in each insured unit. From the dekad rainfall of Chapter 6 it finds the start of the rainy season and of the dry season in every year, takes the typical date over 1991-2020, and from it fixes one transplanting date per unit for each of the two insured seasons, MH and MK1 (Chapter 1, section 4). It then lays the seasons and their growth stages over every crop year of the record, so that later chapters can add up the rain of any stage of any season with a join.
NoteLearning objectives
By the end of this chapter you will be able to:
detect the onset of a rainy or a dry season with the window function lead() and min() FILTER;
take a median that is always an observed value with percentile_disc;
count positions in a year that does not start on 1 January, and turn them back into dates;
expand a calendar over many years with generate_series and keep only complete seasons with HAVING;
explain which parts of a crop calendar are measured and which are choices.
Before running this chapter:
complete Chapter 6, which builds the dekad rainfall idx.dekad_rain used here, and the chapters before it;
allow under a minute for the whole chapter. No downloads are needed. A step whose table 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 that the tables of Chapters 3 to 6 that this chapter reads are there. UNIT is the kabupaten/kota the chapter looks at closely (Garut, as in Chapter 6) and CROP_YEAR the crop year used to show the onset rule at work (section 3).
import osos.environ.setdefault("MKL_THREADING_LAYER", "SEQUENTIAL") # before numpy is imported (ledger L128)import datetime as dtimport timefrom pathlib import Pathimport geopandas as gpdimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport psycopgimport yamlfrom psycopg import sqlfrom sqlalchemy import URL, create_engineT0 = time.perf_counter()UNIT ="3205"# BPS code of Kabupaten GarutCROP_YEAR =2019# crop year shown in section 3 (1 August 2019 to 31 July 2020)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 ["ref.kabupaten", "idx.insured_unit", "idx.chirps_dekad", "idx.dekad_rain"]:ifnot conn.execute("SELECT to_regclass(%s)", [table]).fetchone()[0]:raiseRuntimeError(f"{table} is missing: run Chapters 3 to 6 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]print(f"unit looked at: {UNIT}{unit_name} | crop year shown: {CROP_YEAR}")
connected | POSTGIS="3.7.0 3.7.0" [EXTENSION] PGSQL="180" GEOS="3.15.1-C ...
unit looked at: 3205 Garut | crop year shown: 2019
2. Crop years, seasons and positions
Rice in Java is grown in seasons tied to the rains. The series insures two of them (Chapter 1, section 4):
MH (musim hujan), the wet-season crop, transplanted once the rains have set in;
MK1 (musim kemarau pertama), the first dry-season crop, transplanted after the MH harvest and growing into the dry months.
Transplanting is the day the seedlings, raised for some weeks in a nursery (a seedbed), are moved to the field. A published planting calendar exists for Java only on a grid of 0.5 degree (about 55 km), with one date per grid cell (ledger L54); the series needs one per kabupaten/kota and derives it from the rainfall itself.
Two seasons that cross New Year do not fit a calendar year well, so the series counts a crop year from 1 August to 31 July, named after the year it starts in: crop year 2019 runs from 1 August 2019 to 31 July 2020, with its MH transplanted late in 2019 in most units (in January 2020 in a few) and its MK1 in 2020.
Inside a crop year, a dekad is identified by its positionk, the number of dekads since 1 August: k = 0 is 1-10 August, k = 3 is 1-10 September, k = 15 is 1-10 January of the next calendar year. Positions above 35 run into the next crop year. Two small Python helpers turn a position into a readable label and into a date, so that outputs can show “1 Nov” instead of 9.
MONTHS ="Aug Sep Oct Nov Dec Jan Feb Mar Apr May Jun Jul".split()def label(k) ->str:"""Position k (dekads from 1 August) as a label such as '11 Nov'; '+1y' when it lies in the next crop year.""" y, r =divmod(int(k), 36)returnf"{(1, 11, 21)[r %3]}{MONTHS[r //3]}"+ (f" +{y}y"if y else"")def k_to_date(crop_year: int, k: int) -> dt.date:"""First day of the dekad at position k of a crop year.""" months, part =divmod(int(k), 3) year, month =divmod(7+ months, 12) # 7 = August, counting months from January = 0return dt.date(crop_year + year, month +1, 1+10* part)print([(k, label(k), k_to_date(2019, k)) for k in (0, 3, 9, 15, 28, 36)])
In SQL the same conversions are short expressions, used in the queries below:
the crop year of a dekad_start d: extract(year FROM d), minus 1 if extract(month FROM d) is before 8 (August);
the position of d in crop year y: (extract(year FROM d) - y) * 36 + (extract(month FROM d) - 8) * 3 + (extract(day FROM d) - 1) / 10, where the last term is 0, 1 or 2 for a dekad starting on the 1st, 11th or 21st. extract returns a numeric, so each part is cast to int first and the division by 10 drops the remainder.
The stages of the crop
A rice crop passes through three phases. For a 120-day tropical variety, Yoshida (1981) gives about 60 days in the vegetative phase, 30 in the reproductive and 30 in ripening, and most of the difference between short and long varieties lies in the vegetative phase (ledger L56). The series gives the crop 10 dekads in the field after transplanting: 3 reproductive and 3 ripening, as in Yoshida, and 4 vegetative. Yoshida’s vegetative phase is longer because the series counts the time in the nursery as part of it and leaves it out of the field season; how long the nursery lasts is a choice of the series (2 dekads, section 5), not a measured value. The table is small, so it is written by hand.
withconnect() as conn:if conn.execute("SELECT to_regclass('idx.crop_stage')").fetchone()[0]:print("idx.crop_stage already exists: left as it is")else: conn.execute(""" CREATE TABLE idx.crop_stage ( stage text PRIMARY KEY, stage_no smallint NOT NULL UNIQUE, first_dekad smallint NOT NULL, last_dekad smallint NOT NULL, CHECK (first_dekad BETWEEN 1 AND last_dekad))""") conn.execute("""INSERT INTO idx.crop_stage VALUES ('vegetative', 1, 1, 4), ('reproductive', 2, 5, 7), ('ripening', 3, 8, 10)""") conn.execute(sql.SQL("COMMENT ON TABLE idx.crop_stage IS {}").format(sql.Literal("Rice growth stages in dekads after transplanting, 4/3/3 (reproductive and ripening after Yoshida 1981, "f"ledger L56; the nursery counted outside); built {dt.date.today()} by Chapter 7"))) stages = pd.DataFrame(conn.execute("SELECT * FROM idx.crop_stage ORDER BY stage_no").fetchall(), columns=["stage", "stage_no", "first_dekad", "last_dekad"])stages
stage
stage_no
first_dekad
last_dekad
0
vegetative
1
1
4
1
reproductive
2
5
7
2
ripening
3
8
10
3. When does the rainy season start?
Indonesia’s meteorological agency BMKG defines the onset of the rainy season as the first of three consecutive dekads (dasarian) with at least 50 mm each, and the onset of the dry season as the reverse (ledger L55), which the series reads as the first of three consecutive dekads with less than 50 mm each. BMKG applies the rule to the rain of its own seasonal zones; the series applies it to the paddy-weighted rain of each insured unit, for all paddy together (regime all of Chapter 6). The index of the next chapters also uses all: for it, the three regimes rank the seasons almost alike (ledger L62).
The rule needs, for each dekad, the rain of the next two. The window function lead(mm, n) OVER w returns the value n rows further on in the order the window w defines, so one row can see its two successors. The query shows the rule at work for UNIT in the wet-season months of CROP_YEAR. WINDOW w AS (ORDER BY dekad_start) names the window once for both lead calls; coalesce(..., false) turns the test into false where a successor is missing at the end of the record.
ONSET_DEMO ="""WITH r AS ( SELECT dekad_start, mm, lead(mm, 1) OVER w AS mm_next, lead(mm, 2) OVER w AS mm_after FROM idx.dekad_rain WHERE kabupaten_code = %(u)s AND regime = 'all' WINDOW w AS (ORDER BY dekad_start))SELECT dekad_start, round(mm::numeric, 1) AS mm, round(mm_next::numeric, 1) AS mm_next, round(mm_after::numeric, 1) AS mm_after, coalesce(mm >= 50 AND mm_next >= 50 AND mm_after >= 50, false) AS starts_wet_runFROM rWHERE dekad_start >= make_date(%(y)s, 9, 1) AND dekad_start < make_date(%(y)s + 1, 1, 1)ORDER BY dekad_start"""demo = pd.read_sql(ONSET_DEMO, ENGINE, params={"u": UNIT, "y": CROP_YEAR})first = demo[demo.starts_wet_run].dekad_start.min()print(f"{unit_name}, crop year {CROP_YEAR}: first dekad that starts three wet dekads: {first}")demo
Garut, crop year 2019: first dekad that starts three wet dekads: 2019-11-21
dekad_start
mm
mm_next
mm_after
starts_wet_run
0
2019-09-01
9.3
3.6
3.9
False
1
2019-09-11
3.6
3.9
17.8
False
2
2019-09-21
3.9
17.8
7.8
False
3
2019-10-01
17.8
7.8
2.4
False
4
2019-10-11
7.8
2.4
23.2
False
5
2019-10-21
2.4
23.2
28.2
False
6
2019-11-01
23.2
28.2
54.0
False
7
2019-11-11
28.2
54.0
70.0
False
8
2019-11-21
54.0
70.0
166.3
True
9
2019-12-01
70.0
166.3
167.2
True
10
2019-12-11
166.3
167.2
77.8
True
11
2019-12-21
167.2
77.8
51.1
True
Look before moving on. The onset is the first row where starts_wet_run is true. Note the order of work in the query: the CTE r computes lead over the unit’s whole record and only then does the outer query keep September to December. A window function sees only the rows that reach it, so filtering first would leave the last dekads of December without successors (NULL) and the rule could not be tested there.
One onset per year is not yet a calendar. The next query finds the onset of every crop year 1991-2020 for UNIT. min(...) FILTER (WHERE ...) takes the earliest position among the dekads that meet the rule, searching from 1 September to the end of February (the search window of the series); a crop year with no such dekad gets NULL.
ONSET_YEARS ="""WITH r AS ( SELECT dekad_start, mm, lead(mm, 1) OVER w AS mm_next, lead(mm, 2) OVER w AS mm_after FROM idx.dekad_rain WHERE kabupaten_code = %(u)s AND regime = 'all' WINDOW w AS (ORDER BY dekad_start)),y AS ( SELECT r.*, extract(year FROM dekad_start)::int - CASE WHEN extract(month FROM dekad_start) >= 8 THEN 0 ELSE 1 END AS crop_year FROM r)SELECT crop_year, min((extract(year FROM dekad_start)::int - crop_year) * 36 + (extract(month FROM dekad_start)::int - 8) * 3 + (extract(day FROM dekad_start)::int - 1) / 10) FILTER (WHERE mm >= 50 AND mm_next >= 50 AND mm_after >= 50 AND dekad_start >= make_date(crop_year, 9, 1) AND dekad_start < make_date(crop_year + 1, 3, 1)) AS onset_kFROM yWHERE crop_year BETWEEN 1991 AND 2020GROUP BY crop_year ORDER BY crop_year"""onsets = pd.read_sql(ONSET_YEARS, ENGINE, params={"u": UNIT})fig, ax = plt.subplots(figsize=(9, 3.2))ax.scatter(onsets.crop_year, onsets.onset_k, s=16)ticks =range(int(onsets.onset_k.min()), int(onsets.onset_k.max()) +1, 3)ax.set_yticks(list(ticks), [label(k) for k in ticks])ax.set_xlabel("crop year"); ax.set_ylabel("rainy-season onset"); ax.set_title(unit_name)plt.show()print(f"years with an onset: {onsets.onset_k.notna().sum()} of {len(onsets)}; earliest {label(onsets.onset_k.min())}, "f"latest {label(onsets.onset_k.max())}; years with the onset on 1 Sep, the first dekad searched: "f"{(onsets.onset_k ==3).sum()}")
years with an onset: 30 of 30; earliest 1 Sep, latest 1 Dec; years with the onset on 1 Sep, the first dekad searched: 2
Look before moving on. The onset moves by weeks from one year to the next. A contract could follow each year’s onset, but then the dates of the insured stages would only be known once the season had begun. Tested on MK1 drought windows against the reported damage of 2016-2025, windows timed from each year’s onset ranked the damage no better than windows timed from the median onset (pooled AUC 0.686 against 0.706, ledger L52). The AUC is the chance that a unit-year with damage gets a drier window than one without; 0.5 is no better than a coin toss, and Chapter 11 uses it in full. The series therefore fixes one date per unit: the median onset over the 30 crop years 1991-2020, the reference period the index uses in Chapter 8.
An onset on 1 September, the first dekad searched, means the rains may have set in before the search began: across the insured units that happens in 121 of 2,970 unit-years, 99 of them with the dekad of 21 August already wet (ledger L163). Such years pull a unit’s median early. Searching from 1 August instead changes the onset in 6% of unit-years (ledger L50); the series keeps 1 September.
A median that is a real dekad
The median comes from an ordered-set aggregate, an aggregate that needs its input in order, written with WITHIN GROUP (ORDER BY ...). percentile_cont(0.5) interpolates between the two middle values when their number is even; percentile_disc(0.5) returns a value that occurs in the data, the lower of the two middle values, so the median onset is always a real dekad. Ordered-set aggregates leave NULL values out. The cell runs both on the onsets of UNIT (the query above, used as a subquery).
withconnect() as conn: disc, cont, n = conn.execute(f"""SELECT percentile_disc(0.5) WITHIN GROUP (ORDER BY onset_k), percentile_cont(0.5) WITHIN GROUP (ORDER BY onset_k), count(onset_k) FROM ({ONSET_YEARS}) o""", {"u": UNIT}).fetchone()print(f"{unit_name}: {n} onsets, percentile_disc {disc} ({label(disc)}), percentile_cont {cont}")
Here the query text of ONSET_YEARS is pasted into another query as a subquery with an f-string. That is safe because it is a fixed string written in this notebook; values that come from outside are always passed as parameters (%(u)s), never pasted in.
4. When does the dry season start?
The MK1 crop is planted near the end of the rains and grows into the dry months, so its date comes from the other end of the wet season: the dry-season onset, the first of three consecutive dekads with less than 50 mm each. It is searched in each calendar year from 1 March to 21 November, the search window of the series: the dry season starts and ends within one calendar year, so here the calendar year groups the dekads, not the crop year. In a calendar year the dekad index dk = (month - 1) * 3 + (day - 1) / 10 runs from 0 (1 January) to 35, so the search runs over dk 6 to 32. The cell lists the dry-season onsets of UNIT for the last years of the reference period.
DRY_YEARS ="""WITH r AS ( SELECT dekad_start, mm, lead(mm, 1) OVER w AS mm_next, lead(mm, 2) OVER w AS mm_after FROM idx.dekad_rain WHERE kabupaten_code = %(u)s AND regime = 'all' WINDOW w AS (ORDER BY dekad_start)),c AS ( SELECT r.*, extract(year FROM dekad_start)::int AS cal_year, (extract(month FROM dekad_start)::int - 1) * 3 + (extract(day FROM dekad_start)::int - 1) / 10 AS dk FROM r)SELECT cal_year, min(dk) FILTER (WHERE mm < 50 AND mm_next < 50 AND mm_after < 50 AND dk BETWEEN 6 AND 32) AS onset_dkFROM cWHERE cal_year BETWEEN 1991 AND 2020GROUP BY cal_year ORDER BY cal_year"""dry = pd.read_sql(DRY_YEARS, ENGINE, params={"u": UNIT})dry["onset"] = [label(dk +15) if pd.notna(dk) elseNonefor dk in dry.onset_dk] # dk + 15 = position from 1 Augustprint(f"years with a dry-season onset: {dry.onset_dk.notna().sum()} of {len(dry)}; "f"without: {dry[dry.onset_dk.isna()].cal_year.tolist()}")dry.tail(6)
years with a dry-season onset: 27 of 30; without: [1998, 2010, 2016]
cal_year
onset_dk
onset
24
2015
13.0
11 May
25
2016
NaN
NaN
26
2017
18.0
1 Jul
27
2018
12.0
1 May
28
2019
13.0
11 May
29
2020
16.0
11 Jun
Look before moving on. The onsets should fall around the middle of the year. A year without an onset (NaN) had no three consecutive dekads under 50 mm between March and November: a dry season that never became dry by this rule. The median leaves such years out, and since they are the wettest dry seasons, the unit’s median dry-season onset comes out somewhat earlier than if they counted.
dk + 15 turns a dekad of the calendar year into a position from the previous 1 August, since 1 January is position 15. That puts both onsets on one scale: the MK1 of crop year 2019 is planted in 2020, at a position after the MH of the same crop year.
5. The calendar of every unit
The rules for the two transplanting dates combine the measured onsets with choices of this series:
MH: the unit’s median wet-season onset plus 2 dekads, taken as the time from sowing the nursery at the onset to transplanting;
MK1: the unit’s median dry-season onset minus 2 dekads, so that the crop is established on the last rains of the wet season; but at the earliest at MH transplanting + 11 dekads, which leaves at least one free dekad between the end of the 10-dekad MH season and MK1.
The offsets of 2 dekads and the one free dekad are illustrative choices, not measured nursery times or farmers’ dates.
The MK1 rule also has a history the reader should know. It was chosen after seeing when drought damage is reported: against the drought damage of 2016-2025, windows timed from the dry-season onset ranked the damage better than three other dates when all years are pooled, but no better within a single year, where all four scored about 0.5, the level of chance (ledger L52). Its edge is therefore a hypothesis, not a test result, and Chapter 11, which uses the same damage reports, cannot settle it either.
The build runs the onset queries of sections 3 and 4 for all insured units at once (PARTITION BY kabupaten_code restarts lead for each unit), takes the medians and applies the two rules. greatest() applies the “at the earliest” condition, and clamped records where it moved the MK1 date. The result has one row per unit and season; it builds in about a second.
CROP_CALENDAR ="""CREATE TABLE idx.crop_calendar ASWITH r AS ( -- each dekad with the rain of the next two SELECT kabupaten_code, dekad_start, mm, lead(mm, 1) OVER w AS mm1, lead(mm, 2) OVER w AS mm2 FROM idx.dekad_rain WHERE regime = 'all' AND kabupaten_code IN (SELECT code FROM idx.insured_unit) WINDOW w AS (PARTITION BY kabupaten_code ORDER BY dekad_start)),rk AS ( -- crop year, calendar year, dekad of the calendar year SELECT r.*, extract(year FROM dekad_start)::int - CASE WHEN extract(month FROM dekad_start) >= 8 THEN 0 ELSE 1 END AS crop_year, extract(year FROM dekad_start)::int AS cal_year, (extract(month FROM dekad_start)::int - 1) * 3 + (extract(day FROM dekad_start)::int - 1) / 10 AS dk FROM r),wet AS ( -- wet-season onset per unit and crop year 1991-2020 SELECT kabupaten_code, crop_year, min((extract(year FROM dekad_start)::int - crop_year) * 36 + (extract(month FROM dekad_start)::int - 8) * 3 + (extract(day FROM dekad_start)::int - 1) / 10) FILTER (WHERE mm >= 50 AND mm1 >= 50 AND mm2 >= 50 AND dekad_start >= make_date(crop_year, 9, 1) AND dekad_start < make_date(crop_year + 1, 3, 1)) AS onset_k FROM rk WHERE crop_year BETWEEN 1991 AND 2020 GROUP BY kabupaten_code, crop_year),dry AS ( -- dry-season onset per unit and calendar year 1991-2020 SELECT kabupaten_code, cal_year, min(dk) FILTER (WHERE mm < 50 AND mm1 < 50 AND mm2 < 50 AND dk BETWEEN 6 AND 32) AS onset_dk FROM rk WHERE cal_year BETWEEN 1991 AND 2020 GROUP BY kabupaten_code, cal_year),clim AS ( -- medians over 1991-2020, with the number of years found SELECT w.kabupaten_code, w.wet_onset_k, w.wet_years, d.dry_onset_k, d.dry_years FROM (SELECT kabupaten_code, percentile_disc(0.5) WITHIN GROUP (ORDER BY onset_k) AS wet_onset_k, count(onset_k) AS wet_years FROM wet GROUP BY kabupaten_code) w JOIN (SELECT kabupaten_code, percentile_disc(0.5) WITHIN GROUP (ORDER BY onset_dk) + 15 AS dry_onset_k, count(onset_dk) AS dry_years FROM dry GROUP BY kabupaten_code) d USING (kabupaten_code))SELECT kabupaten_code, 'MH'::text AS season, (wet_onset_k + 2)::smallint AS transplant_k, wet_onset_k::smallint AS onset_k, wet_years::smallint AS onset_years, false AS clampedFROM climUNION ALLSELECT kabupaten_code, 'MK1', greatest(dry_onset_k - 2, wet_onset_k + 2 + 10 + 1)::smallint, dry_onset_k::smallint, dry_years::smallint, dry_onset_k - 2 < wet_onset_k + 2 + 10 + 1FROM clim"""withconnect() as conn:if conn.execute("SELECT to_regclass('idx.crop_calendar')").fetchone()[0]:print("idx.crop_calendar already exists: left as it is")else: t = time.perf_counter() conn.execute(CROP_CALENDAR) conn.execute("""ALTER TABLE idx.crop_calendar ADD PRIMARY KEY (kabupaten_code, season), ADD FOREIGN KEY (kabupaten_code) REFERENCES idx.insured_unit (code), ADD CHECK (season IN ('MH', 'MK1')), ALTER COLUMN transplant_k SET NOT NULL, ALTER COLUMN onset_k SET NOT NULL, ALTER COLUMN clamped SET NOT NULL""") conn.execute(sql.SQL("COMMENT ON TABLE idx.crop_calendar IS {}").format(sql.Literal("Transplanting position per insured unit and season, in dekads from 1 August of the crop year: MH = median ""1991-2020 BMKG wet-season onset + 2; MK1 = median 1991-2020 dry-season onset - 2, at the earliest MH "f"transplanting + 11 (clamped); built {dt.date.today()} by Chapter 7"))) conn.execute("ANALYZE idx.crop_calendar")print(f"idx.crop_calendar built in {time.perf_counter() - t:.1f} s") cal = pd.DataFrame(conn.execute("""SELECT c.kabupaten_code, u.name, c.season, c.transplant_k, c.onset_k, c.onset_years, c.clamped FROM idx.crop_calendar c JOIN idx.insured_unit u ON u.code = c.kabupaten_code ORDER BY 1, 3""").fetchall(), columns=["code", "name", "season", "transplant_k", "onset_k", "onset_years", "clamped"])for season, g in cal.groupby("season"): q = g.transplant_k.quantile([0, 0.5, 1], interpolation="lower").astype(int)print(f"{season}: {len(g)} units; transplanting earliest {label(q[0])}, median {label(q[0.5])}, latest {label(q[1])}; "f"onset found in at least {g.onset_years.min()} of 30 years per unit; clamped: {int(g.clamped.sum())}")print("clamped units:", cal[cal.clamped].name.tolist())cal[cal.code == UNIT].assign(transplant=lambda d: d.transplant_k.map(label), onset=lambda d: d.onset_k.map(label))
idx.crop_calendar built in 0.8 s
MH: 99 units; transplanting earliest 11 Oct, median 1 Dec, latest 11 Jan; onset found in at least 27 of 30 years per unit; clamped: 0
MK1: 99 units; transplanting earliest 1 Apr, median 21 Apr, latest 21 May; onset found in at least 21 of 30 years per unit; clamped: 6
clamped units: ['Banyuwangi', 'Situbondo', 'Probolinggo', 'Kota Probolinggo', 'Kota Pasuruan', 'Kota Serang']
code
name
season
transplant_k
onset_k
onset_years
clamped
transplant
onset
8
3205
Garut
MH
10
8
30
False
11 Nov
21 Oct
9
3205
Garut
MK1
29
31
27
False
21 May
11 Jun
Look before moving on. Every insured unit should have one MH and one MK1 row. As a rough outside check, the published grid calendar for Java (ledger L54) plants its main season from 25 October to 10 December and its second season around 10 May: compare the median dates printed above. In the table for UNIT, onset_k is the wet-season onset on the MH row and the dry-season onset on the MK1 row. The number of years with an onset (onset_years) shows how firmly each median rests on the data; the series sets no minimum, so read a unit with few years with care. The clamped units are those where the dry season starts so early that the MK1 date would come too close to the MH harvest.
The gap between the two seasons is worth a look too. The dekads from the end of the MH season (transplanting + 10) to the MK1 transplanting are free, and so are those from the end of MK1 to the next MH, 36 positions later; the free dekads after MK1 are where a second dry-season crop (MK2), which the series does not insure, would go.
wide = cal.pivot(index=["code", "name"], columns="season", values="transplant_k").reset_index()wide["free_after_MH"] = wide.MK1 - (wide.MH +10)wide["free_after_MK1"] = wide.MH +36- (wide.MK1 +10)print(f"free dekads after the MH season: min {wide.free_after_MH.min()}, median {wide.free_after_MH.median():.0f}, "f"max {wide.free_after_MH.max()}; after the MK1 season: min {wide.free_after_MK1.min()}")wide.sort_values("free_after_MH", ascending=False).head(5)
free dekads after the MH season: min 1, median 4, max 12; after the MK1 season: min 4
season
code
name
MH
MK1
free_after_MH
free_after_MK1
0
3201
Bogor
7
29
12
4
20
3278
Kota Tasikmalaya
8
29
11
5
93
3602
Lebak
8
29
11
5
92
3601
Pandeglang
8
29
11
5
6
3207
Ciamis
9
29
10
6
Units with many free dekads after the MH season could fit another crop in between, or plant MK1 earlier than the dry-season rule says; the calendar models neither. These are the limits of one rule for all of Java, and a reason to read the MK1 date of such a unit with care.
The maps show how the two dates vary across Java, MH on top and MK1 below. The boundaries are simplified for drawing as in Chapter 3, in a CTE over ref.kabupaten alone before the join: ST_CoverageSimplify needs each polygon once, and the join gives every insured unit two rows. ST_SetSRID(..., 4326) restores the coordinate system, which ST_CoverageSimplify returns as 0 in this PostGIS version (ledger L163). The cell also prints the median dates per province (the first two digits of the BPS code).
MAP ="""WITH k AS (SELECT code, ST_SetSRID(ST_CoverageSimplify(geometry, 0.005) OVER (), 4326) AS geometry FROM ref.kabupaten)SELECT k.code, c.season, c.transplant_k, k.geometryFROM k LEFT JOIN idx.crop_calendar c ON c.kabupaten_code = k.code"""m = gpd.read_postgis(MAP, ENGINE, geom_col="geometry")base = m.drop_duplicates("code")fig, axes = plt.subplots(2, 1, figsize=(10, 6.6))for ax, season inzip(axes, ["MH", "MK1"]): s = m[m.season == season] base.plot(ax=ax, color="0.85", edgecolor="white", linewidth=0.3) s.plot(ax=ax, column="transplant_k", cmap="viridis", edgecolor="white", linewidth=0.3) lo, hi =int(s.transplant_k.min()), int(s.transplant_k.max()) sm = plt.cm.ScalarMappable(cmap="viridis", norm=plt.Normalize(lo, hi)) cb = fig.colorbar(sm, ax=ax, shrink=0.8) ticks =list(range(lo, hi +1, max(1, (hi - lo) //4))) cb.set_ticks(ticks, labels=[label(k) for k in ticks]) ax.set_title(f"{season} transplanting"); ax.set_axis_off()plt.tight_layout()plt.show()names = pd.read_sql("SELECT code AS prov, name AS province FROM ref.province", ENGINE)by_prov = (cal.assign(prov=cal.code.str[:2]).groupby(["prov", "season"]).transplant_k .quantile(0.5, interpolation="lower").astype(int).map(label).unstack().reset_index())by_prov.merge(names, on="prov")[["prov", "province", "MH", "MK1"]]
prov
province
MH
MK1
0
32
Jawa Barat
11 Nov
11 May
1
33
Jawa Tengah
11 Nov
1 May
2
34
Daerah Istimewa Yogyakarta
21 Nov
11 Apr
3
35
Jawa Timur
11 Dec
11 Apr
4
36
Banten
1 Dec
11 May
Look before moving on. The per-province medians summarise the maps: compare the provinces in the west with those in the east, for each season. Neighbouring units should mostly have similar dates; a unit that stands out from all its neighbours is worth a look at its onsets.
6. Laying the seasons over the record
The calendar gives positions; the index needs dates. idx.season_dekad lists, for every unit, season and crop year, the ten dekads of the season with their stage and their dekad_start, so that a join to idx.dekad_rain on unit and date gives the rain of each dekad of each season.
generate_series(1980, last) produces the crop years and generate_series(1, 10) the dekads of a season; their cross join with the calendar makes every combination, and the join to idx.crop_stage names the stage. last is the year of the last dekad in idx.chirps_dekad, so the table grows when the record is extended.
The position k = transplant_k + n - 1 becomes a date: make_interval(months => k / 3) added to 1 August of the crop year gives a timestamp, which ::date turns back into a date, and mod(k, 3) * 10 days move it to the 11th or 21st.
The crop years start at 1980 because the MK1 of crop year 1980 is planted in 1981, inside the record.
The row comparison (a, b, c) IN (SELECT ...) keeps a unit-season-year only if it is among those whose ten dekads all exist in idx.chirps_dekad (HAVING count(*) = 10): a season that starts before the record or ends after it would be incomplete.
MK1 runs past 31 July in some units, so a dekad in August can belong to the MK1 of the previous crop year: later chapters take crop_year from this table and never derive it again from dekad_start.
SEASON_DEKAD ="""CREATE TABLE idx.season_dekad ASWITH s AS ( SELECT c.kabupaten_code, c.season, y AS crop_year, n AS dekad_no, st.stage, c.transplant_k + n - 1 AS k FROM idx.crop_calendar c CROSS JOIN generate_series(1980, (SELECT extract(year FROM max(dekad_start))::int FROM idx.chirps_dekad)) AS y CROSS JOIN generate_series(1, 10) AS n JOIN idx.crop_stage st ON n BETWEEN st.first_dekad AND st.last_dekad),d AS ( SELECT s.*, (make_date(crop_year, 8, 1) + make_interval(months => k / 3))::date + mod(k, 3) * 10 AS dekad_start FROM s)SELECT d.kabupaten_code, d.season, d.crop_year, d.dekad_no, d.stage, d.dekad_startFROM dWHERE (d.kabupaten_code, d.season, d.crop_year) IN ( SELECT d2.kabupaten_code, d2.season, d2.crop_year FROM d d2 JOIN idx.chirps_dekad cd ON cd.dekad_start = d2.dekad_start GROUP BY 1, 2, 3 HAVING count(*) = 10)"""withconnect() as conn:if conn.execute("SELECT to_regclass('idx.season_dekad')").fetchone()[0]:print("idx.season_dekad already exists: left as it is")else: t = time.perf_counter() conn.execute(SEASON_DEKAD) conn.execute("""ALTER TABLE idx.season_dekad ADD PRIMARY KEY (kabupaten_code, season, crop_year, dekad_no), ADD FOREIGN KEY (kabupaten_code, season) REFERENCES idx.crop_calendar (kabupaten_code, season), ADD FOREIGN KEY (stage) REFERENCES idx.crop_stage (stage)""") conn.execute("CREATE INDEX ON idx.season_dekad (kabupaten_code, dekad_start)") conn.execute(sql.SQL("COMMENT ON TABLE idx.season_dekad IS {}").format(sql.Literal("idx.crop_calendar laid over the CHIRPS record: unit x season x crop year x dekad 1-10 with stage and "f"dekad_start; complete seasons only; built {dt.date.today()} by Chapter 7"))) conn.execute("ANALYZE idx.season_dekad")print(f"idx.season_dekad built in {time.perf_counter() - t:.1f} s") years = pd.DataFrame(conn.execute(""" SELECT season, min(crop_year), max(crop_year), count(DISTINCT crop_year), count(*), count(DISTINCT kabupaten_code) FILTER (WHERE crop_year = 1980) FROM idx.season_dekad GROUP BY season ORDER BY season""").fetchall(), columns=["season", "first_crop_year", "last_crop_year", "crop_years", "rows", "units_1980"])example = pd.read_sql("""SELECT season, crop_year, dekad_no, stage, dekad_start FROM idx.season_dekad WHERE kabupaten_code = %(u)s AND crop_year = %(y)s ORDER BY season, dekad_no""", ENGINE, params={"u": UNIT, "y": CROP_YEAR})print(years.to_string(index=False))starts = example.groupby("season").dekad_start.min()for season, k in cal[cal.code == UNIT].set_index("season").transplant_k.items():print(f"{season}: first dekad {starts[season]} | k_to_date({CROP_YEAR}, {k}) = {k_to_date(CROP_YEAR, k)}")example
idx.season_dekad built in 1.6 s
season first_crop_year last_crop_year crop_years rows units_1980
MH 1980 2025 46 44590 4
MK1 1980 2025 46 45540 99
MH: first dekad 2019-11-11 | k_to_date(2019, 10) = 2019-11-11
MK1: first dekad 2020-05-21 | k_to_date(2019, 29) = 2020-05-21
season
crop_year
dekad_no
stage
dekad_start
0
MH
2019
1
vegetative
2019-11-11
1
MH
2019
2
vegetative
2019-11-21
2
MH
2019
3
vegetative
2019-12-01
3
MH
2019
4
vegetative
2019-12-11
4
MH
2019
5
reproductive
2019-12-21
5
MH
2019
6
reproductive
2020-01-01
6
MH
2019
7
reproductive
2020-01-11
7
MH
2019
8
ripening
2020-01-21
8
MH
2019
9
ripening
2020-02-01
9
MH
2019
10
ripening
2020-02-11
10
MK1
2019
1
vegetative
2020-05-21
11
MK1
2019
2
vegetative
2020-06-01
12
MK1
2019
3
vegetative
2020-06-11
13
MK1
2019
4
vegetative
2020-06-21
14
MK1
2019
5
reproductive
2020-07-01
15
MK1
2019
6
reproductive
2020-07-11
16
MK1
2019
7
reproductive
2020-07-21
17
MK1
2019
8
ripening
2020-08-01
18
MK1
2019
9
ripening
2020-08-11
19
MK1
2019
10
ripening
2020-08-21
Look before moving on. In the example, the ten dekads of each season should follow one another without a gap, with dates on the 1st, 11th and 21st, and the stages should change after dekads 4 and 7; the first dekad of each season should equal the Python helper’s date. Check also the first and last crop years and the counts:
crop year 1980 appears only where its season lies wholly after 1 January 1981, the start of the record: for MK1 in every unit, for MH only in the few units transplanted in January (units_1980);
crop year 2025 is the last complete one for both seasons; the seasons of crop year 2026 lie after the end of the record (September 2026, Chapter 4), so HAVING drops them;
Chapter 8 uses the crop years 1981-2025, which every unit has for both seasons.
7. Rain by season and stage
With idx.season_dekad the rain of any season or stage is a join and a GROUP BY. The query sums the dekad rain of UNIT per season and crop year; the figure shows both seasons over the whole record, and the table describes the season totals of 1991-2020.
season_rain = pd.read_sql(""" SELECT s.season, s.crop_year, sum(r.mm) AS mm FROM idx.season_dekad s JOIN idx.dekad_rain r ON r.kabupaten_code = s.kabupaten_code AND r.regime = 'all' AND r.dekad_start = s.dekad_start WHERE s.kabupaten_code = %(u)s GROUP BY s.season, s.crop_year ORDER BY s.season, s.crop_year""", ENGINE, params={"u": UNIT})fig, ax = plt.subplots(figsize=(9, 3.2))for season, g in season_rain.groupby("season"): ax.plot(g.crop_year, g.mm, marker=".", label=season)ax.set_xlabel("crop year"); ax.set_ylabel("season rainfall (mm)"); ax.set_title(unit_name); ax.legend()plt.show()season_rain[(season_rain.crop_year >=1991) & (season_rain.crop_year <=2020)].groupby("season").mm.describe().round(0)
count
mean
std
min
25%
50%
75%
max
season
MH
30.0
1151.0
176.0
791.0
1057.0
1152.0
1203.0
1596.0
MK1
30.0
362.0
280.0
82.0
139.0
288.0
496.0
1113.0
Look before moving on. Compare the two rows of the table: MH gets far more rain than MK1 in this unit, and MK1 varies much more relative to its mean (compare std with mean, and min with max). It is this spread of the MK1 seasons that a drought index ranks.
The last figure draws the unit’s rainfall over a crop year with the two seasons and their stages on top: the mean rain of each position over the crop years 1991-2020, repeated after 36 positions so that an MK1 running past 31 July stays in one piece. In the query, mod(month + 4, 12) counts the months since August (August gives 0, January 5).
normal = pd.read_sql(""" SELECT mod(extract(month FROM dekad_start)::int + 4, 12) * 3 + (extract(day FROM dekad_start)::int - 1) / 10 AS k, avg(mm) AS mm FROM idx.dekad_rain WHERE kabupaten_code = %(u)s AND regime = 'all' AND dekad_start >= '1991-08-01' AND dekad_start < '2021-08-01' GROUP BY 1 ORDER BY 1""", ENGINE, params={"u": UNIT})ks = np.arange(0, 48)fig, ax = plt.subplots(figsize=(10, 3.6))ax.bar(ks, normal.set_index("k").mm.reindex(ks %36).to_numpy(), color="0.75", width=0.9, label="mean dekad rain")colours = {"vegetative": "tab:green", "reproductive": "tab:orange", "ripening": "tab:brown"}top = normal.mm.max() *1.15for row, season inenumerate(["MH", "MK1"]): start =int(cal[(cal.code == UNIT) & (cal.season == season)].transplant_k.iloc[0])for _, st in stages.iterrows(): first_k = start + st.first_dekad -1# position of the stage's first dekad ax.broken_barh([(first_k -0.5, st.last_dekad - st.first_dekad +1)], # bars are centred on positions (top * (1.02+0.08* row), top *0.06), color=colours[st.stage], label=st.stage if row ==0elseNone) ax.text(start -2, top * (1.05+0.08* row), season, ha="right", va="center", fontsize=8)ax.axhline(50, color="0.4", linewidth=0.6, linestyle="--")ax.set_xticks(range(0, 48, 3), [label(k) for k inrange(0, 48, 3)], fontsize=7, rotation=45)ax.set_ylabel("mm per dekad"); ax.set_title(f"{unit_name}: mean dekad rain 1991-2020 and the two seasons")ax.legend(fontsize=7, loc="upper left", ncols=4)plt.tight_layout()plt.show()
Look before moving on. MH should sit in the wet months. MK1 should start near the end of the rains, with its reproductive and ripening stages over the bars below the dashed 50 mm line, the threshold of the onset rules. Those are the months of the reported drought damage: in the 99 insured units, 88.5% of the rice area reported as affected by drought (terkena) in 2016-2025 fell in April to September (ledger L49), the months MK1 grows in plus one month, in case damage is reported late. The next chapter turns the rain of each stage into a drought index by comparing it with the stage’s normal rain over 1991-2020.
Checkpoint
The cell below checks, in a new session, what Chapter 8 relies on:
an MH and an MK1 date with an onset for every insured unit, MK1 at least one dekad after the end of the MH season, and the next MH after the end of MK1;
exactly one stage for each of the dekads 1 to 10;
in idx.season_dekad, ten dekads for every unit, season and crop year it holds, one per dekad and spanning 9 dekad steps (87 to 93 days, since dekads last 8 to 11 days), each a dekad of idx.dekad_rain;
every unit and season complete from 1981 to the same last crop year.
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] per_season =dict(conn.execute("SELECT season, count(onset_k) FROM idx.crop_calendar GROUP BY season").fetchall()) overlap = first_row("""SELECT count(*) FROM idx.crop_calendar mh JOIN idx.crop_calendar k1 USING (kabupaten_code) WHERE mh.season = 'MH' AND k1.season = 'MK1' AND (k1.transplant_k < mh.transplant_k + 11 OR mh.transplant_k + 36 < k1.transplant_k + 10)""")[0] stage_ok = first_row("""SELECT count(*) FROM generate_series(1, 10) AS n WHERE (SELECT count(*) FROM idx.crop_stage WHERE n BETWEEN first_dekad AND last_dekad) <> 1""")[0] bad_seasons = first_row("""SELECT count(*) FROM ( SELECT kabupaten_code, season, crop_year FROM idx.season_dekad GROUP BY 1, 2, 3 HAVING count(*) <> 10 OR count(DISTINCT dekad_start) <> 10 OR max(dekad_start) - min(dekad_start) NOT BETWEEN 87 AND 93) s""")[0] no_rain = first_row("""SELECT count(*) FROM idx.season_dekad s WHERE NOT EXISTS ( SELECT 1 FROM idx.dekad_rain r WHERE r.kabupaten_code = s.kabupaten_code AND r.regime = 'all' AND r.dekad_start = s.dekad_start)""")[0] span = first_row("""SELECT count(DISTINCT last_year), min(last_year), count(*) FILTER (WHERE n <> last_year - 1980) FROM (SELECT kabupaten_code, season, max(crop_year) AS last_year, count(DISTINCT crop_year) FILTER (WHERE crop_year >= 1981) AS n FROM idx.season_dekad GROUP BY 1, 2) s""")assert per_season == {"MH": n_units, "MK1": n_units}, f"calendar rows with an onset per season: {per_season}, units {n_units}"assert overlap ==0, f"{overlap} units whose seasons overlap"assert stage_ok ==0, f"{stage_ok} dekads of 1-10 without exactly one stage"assert bad_seasons ==0and no_rain ==0, f"seasons not ten consecutive dekads: {bad_seasons}; dekads without rain: {no_rain}"assert span[0] ==1and span[2] ==0, f"last crop years differ ({span[0]} values) or years missing in {span[2]} unit-seasons"print(f"checkpoint passed: {n_units} units x 2 seasons, crop years 1981-{span[1]} complete for each; "f"code cells took {time.perf_counter() - T0:.0f} s since the setup cell")
checkpoint passed: 99 units x 2 seasons, crop years 1981-2025 complete for each; code cells took 19 s since the setup cell
Troubleshooting
Symptom
Cause
Fix
... is missing: run Chapters 3 to 6 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
section 3 shows no onset for CROP_YEAR
that year has no three wet dekads from September to December in this unit
the demo shows September to December only; the per-year search of the next cell runs to the end of February
idx.crop_calendar already exists, but idx.dekad_rain has changed
the cells never drop a table that later chapters use
drop the tables of this and later chapters, latest first, in one statement (DROP TABLE idx.season_dekad, idx.crop_calendar, ...), then run sections 5 and 6 again
cannot drop table ... because other objects depend on it
a table of a later chapter refers to it with a foreign key
drop the later tables first, as above. Do not add CASCADE: on a referenced table it removes only the foreign key and leaves the later table in place, now out of date
Summary
You now have:
idx.crop_stage: the three growth stages in dekads after transplanting (4, 3 and 3);
idx.crop_calendar: one MH and one MK1 transplanting position per insured unit, from the median wet-season and dry-season onsets of 1991-2020 and offsets chosen by this series;
idx.season_dekad: every complete season of every unit laid over the dekads of the record, with its stage.
On the way you used a window function to look ahead in a series, a median that returns an observed value, a crop year counted from August, and generate_series to expand a rule over many years. The calendar is fixed across years by design: in a year when the rains come early or late, the insured stages do not move with them.
What comes next
Chapter 8 builds the drought index: for each unit, season, crop year and stage, the rain below the stage’s normal of 1991-2020, ranked against the reference years.
References
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), doi:10.31172/jmg.v13i1.113, https://jmg.bmkg.go.id/jmg/index.php/jmg/article/view/113 (ledger L55)