Skip to main content

Chapter 3: Boundaries and reported crop damage

Chapter 3: Boundaries and reported crop damage

TipAt a glance
  • You will build: ref.kabupaten and ref.province (Java’s 119 kabupaten/kota and 6 provinces) and raw.datanonkom_damage (monthly flood, drought and pest damage per kabupaten/kota)
  • You need: Chapter 2; an internet connection on the first run; a 39 MB boundary file and about 540 MB of web pages to download, kept compressed (about 9 MB) in data_dir
  • Time to run: First run: longer than the author’s 23-minute scrape of the same pages (ledger L141), mostly polite pauses between requests; later runs: about 5 minutes (the checkpoint prints the time)
  • Level: Beginner to intermediate

An index insurance contract pays per area, here per kabupaten/kota, and is judged against what happened on the ground. This chapter puts both into the database. First the boundaries of Java’s kabupaten and kota, with a key, valid geometries and a spatial index, and the six provinces built from them in SQL. Then the Ministry of Agriculture’s monthly reports of rice, maize and soybean area damaged by flood, drought and pests, collected from a public web page one request at a time. The damage reports come back in Chapter 11, where payouts are compared with them.

NoteLearning objectives

By the end of this chapter you will be able to:

  • load a vector layer into PostGIS from Python and give the table a primary key, a geometry type, valid geometries and a spatial index;
  • build a coarser layer from a finer one with ST_Union and GROUP BY;
  • find where the BPS and Kemendagri codes of a kabupaten/kota differ, and join on the code your data uses;
  • collect a table from a web page politely: read robots.txt, cache every response, send one request at a time;
  • store “no record”, “zero” and “not reported yet” so that later queries can tell them apart.

Before running this chapter:

  • complete Chapter 2: the database, its extensions and schemas, and config.yml;
  • set data_dir in config.yml to a folder on your computer with about 50 MB free, outside any folder a cloud client syncs (OneDrive, Dropbox). The value shipped, E:/temp/pgci, is the author’s;
  • be online for the first run. It downloads the boundary file and about 200 web pages. The pages come one at a time with a pause between them, so this takes longer than the 23 minutes the author’s scrape of the same pages took (ledger L141). You can stop the cell (Kernel, Interrupt) and run it again at any time: pages already saved are not requested again.

If the damage site is unreachable or refuses the requests, you can still continue: ref.kabupaten and ref.province are built before the scraping starts, and only Chapter 11 uses the damage table.

1. Setup

The setup cell reads config.yml, checks that the drive of data_dir exists, defines connect() as in Chapter 2, and prints the PostGIS version. It also creates ENGINE, a second way into the same database: geopandas reads and writes PostGIS tables through an SQLAlchemy engine rather than a psycopg connection. Both log in with the password file of Chapter 2.

import os
os.environ.setdefault("MKL_THREADING_LAYER", "SEQUENTIAL")   # before numpy is imported (ledger L128)

import datetime as dt
import gzip
import hashlib
import json
import re
import time
from pathlib import Path
from urllib import robotparser

import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
import psycopg
import requests
import yaml
from bs4 import BeautifulSoup
from sqlalchemy import URL, create_engine

T0 = time.perf_counter()

# The repository root, whether the notebook runs from en/, id/ or the root itself
ROOT = Path.cwd() if (Path.cwd() / "tutorial.yml").exists() else Path.cwd().parent
CONFIG = yaml.safe_load((ROOT / "config.yml").read_text(encoding="utf-8"))
DB = CONFIG["database"]
DATA = Path(CONFIG["data_dir"])
if not Path(DATA.anchor).exists():
    raise FileNotFoundError(f"data_dir is {DATA}, on a drive this computer does not have: set data_dir in config.yml")


def connect(**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"]))

with connect() as conn:
    print("connected |", conn.execute("SELECT postgis_full_version()").fetchone()[0][:60], "...")
print("data folder:", DATA)
connected | POSTGIS="3.7.0 3.7.0" [EXTENSION] PGSQL="180" GEOS="3.15.1-C ...
data folder: E:\temp\pgci

2. Administrative units and their codes

Java has six provinces. Each province is divided into kabupaten (regencies) and kota (cities), together called kabupaten/kota, which are divided again into kecamatan (districts). In this series the insured unit is the kabupaten/kota, the finest level at which the damage reports exist (ledger L1).

Two government bodies number these units. Statistics Indonesia (Badan Pusat Statistik, BPS) numbers the areas it uses for statistics, and the Ministry of Home Affairs (Kementerian Dalam Negeri, Kemendagri) the administrative areas; BPS publishes the relation between the two (ledger L138). In Java the two codes agree for 114 of the 119 kabupaten/kota; outside Java they differ more often (ledger L142). The damage reports use the BPS codes (ledger L8), so the BPS code is the key of every table in this series.

The boundaries are those of Badan Informasi Geospasial (BIG), Indonesia’s mapping agency, dated 2022 in the file’s metadata (ledger L139). The file this chapter downloads is that layer cut to the six provinces of Java, with both codes added for this series and the height values (Z) of the vertices dropped (ledger L139). BIG shows the layer on its geoservices portal, which states no terms of use for it (ledger L137).

3. Get the boundary file

The next cell downloads the file named in config.yml if it is not in data_dir yet, and compares its SHA-256 checksum with the one in config.yml. A checksum is a fingerprint of the file’s bytes: if the download was cut short or the file changed, it no longer matches. GeoParquet, the file format, stores a table with a geometry column in a compact, typed form that geopandas reads in one call.

BND = CONFIG["boundaries"]
path = DATA / "boundaries" / BND["file"]
if not path.exists():
    path.parent.mkdir(parents=True, exist_ok=True)
    print("downloading", BND["url"])
    part = path.with_suffix(".part")
    with requests.get(BND["url"], stream=True, timeout=120) as r:
        r.raise_for_status()
        with open(part, "wb") as f:
            for chunk in r.iter_content(1 << 20):
                f.write(chunk)
    part.replace(path)

digest = hashlib.sha256(path.read_bytes()).hexdigest()
if digest != BND["sha256"]:
    raise ValueError(f"{path.name}: checksum {digest} does not match config.yml; delete the file and run again")
print(f"{path} ({path.stat().st_size / 1e6:.1f} MB): checksum matches")

kab = gpd.read_parquet(path)
print("CRS:", kab.crs.to_string(), "|", len(kab), "features |", kab.geom_type.value_counts().to_dict())
kab.drop(columns="geometry").head(8)
E:\temp\pgci\boundaries\java_kabupaten_big2022.parquet (38.9 MB): checksum matches
CRS: EPSG:4326 | 121 features | {'Polygon': 83, 'MultiPolygon': 38}
province_code province_name code name type code_kemendagri
0 35 Jawa Timur 0 NaN NaN 0
1 35 Jawa Timur 0 NaN NaN 0
2 31 DKI Jakarta 3101 Administrasi Kepulauan Seribu Kabupaten Administr* 3101
3 31 DKI Jakarta 3171 Kota Administrasi Jakarta Selatan Kota Administrasi 3174
4 31 DKI Jakarta 3172 Kota Administrasi Jakarta Timur Kota Administrasi 3175
5 31 DKI Jakarta 3173 Kota Administrasi Jakarta Pusat Kota Administrasi 3171
6 31 DKI Jakarta 3174 Kota Administrasi Jakarta Barat Kota Administrasi 3173
7 31 DKI Jakarta 3175 Kota Administrasi Jakarta Utara Kota Administrasi 3172

Look before moving on. The layer is in EPSG:4326 (longitude and latitude). Each row has a province code and name, the BPS code, the name, the type and the Kemendagri code. Two things show already in these eight rows. Jakarta Selatan is 3171 for BPS and 3174 for Kemendagri: section 5 comes back to that. And the first two rows have code 0 and no name, so 121 features are not 121 kabupaten/kota. The next cell lists the rows that cannot be a kabupaten/kota.

kab[(kab.code == "0") | kab.name.isna()].assign(area_ha=lambda d: d.to_crs(6933).area / 1e4).drop(columns="geometry")
province_code province_name code name type code_kemendagri area_ha
0 35 Jawa Timur 0 NaN NaN 0 85.757203
1 35 Jawa Timur 0 NaN NaN 0 12.313478

Two features have code 0 and no name or type: small pieces left over in the source layer, not a kabupaten/kota. They are loaded into the raw copy below and left out of ref.kabupaten, which leaves 119. (The area is computed here in EPSG:6933, an equal-area projection, only to show their size; areas in the database come from geography, as in Chapter 2.)

4. Load the kabupaten/kota into PostGIS

Loading happens in two steps, and this pattern repeats through the series:

  1. raw: the file as received, written by geopandas’ to_postgis into raw.boundary_kabupaten. Nothing depends on this table, so it is simply replaced on every run.
  2. ref: a table designed in SQL and filled from the raw copy.

The raw step first.

kab.to_postgis("boundary_kabupaten", ENGINE, schema="raw", if_exists="replace", index=False)
with connect() as conn:
    print("raw.boundary_kabupaten:", conn.execute("SELECT count(*) FROM raw.boundary_kabupaten").fetchone()[0], "rows")
raw.boundary_kabupaten: 121 rows

Before designing ref.kabupaten, check the geometries. A polygon whose edges cross themselves is invalid, and many PostGIS functions assume valid input: on invalid shapes they can give wrong answers or errors (PostGIS manual, geometry validation). ST_IsValid tests a shape and ST_IsValidReason says what is wrong. The source has one invalid feature among those with a code (ledger L139).

with connect() as conn:
    invalid = conn.execute("""SELECT code, name, ST_IsValidReason(geometry) FROM raw.boundary_kabupaten
                              WHERE code <> '0' AND NOT ST_IsValid(geometry)""").fetchall()
pd.DataFrame(invalid, columns=["code", "name", "reason"])
code name reason
0 3519 Madiun Ring Self-intersection[111.507080621 -7.677644...

Now ref.kabupaten. Its design does the checking:

  • a primary key on the BPS code: no code can appear twice, and other tables can refer to it;
  • a typed geometry column, geometry(MultiPolygon, 4326): PostGIS refuses any other geometry type or coordinate system in it (PostGIS manual, geometry columns). ST_Multi turns single polygons into one-part multipolygons;
  • valid geometries: ST_MakeValid repairs the invalid one, and ST_CollectionExtract(..., 3) keeps only the polygon parts of the repair;
  • a GiST index on the geometry, the spatial index that lets PostGIS find candidate shapes by their bounding boxes instead of testing every row;
  • NOT NULL on name and type: if the two unnamed pieces slipped through the WHERE, the insert would fail.

The type column is kept as in the source: Kabupaten, Kota, Kota Administrasi, and once “Kabupaten Administr*” (Kepulauan Seribu), a value cut to the 20 characters of the source file’s field (ledger L139).

Three more statements finish the table. COMMENT ON TABLE stores a description in the database (obj_description('ref.kabupaten'::regclass) reads it back). ANALYZE collects the statistics PostgreSQL’s planner uses to choose how to run a query. And to_regclass('ref.kabupaten') returns NULL when the table does not exist yet: if it does exist, for example on a second run, the cell leaves it as it is. Everything inside with connect() as conn: is one transaction (Chapter 2), so a failure leaves no half-filled table.

KABUPATEN_DDL = """
CREATE TABLE ref.kabupaten (
    code             char(4)  PRIMARY KEY,           -- BPS code: the key the damage reports use (ledger L8)
    name             text     NOT NULL,
    type             text     NOT NULL,              -- Kabupaten, Kota, Kota Administrasi, as in the source
    province_code    char(2)  NOT NULL,
    code_kemendagri  char(4)  NOT NULL UNIQUE,       -- Ministry of Home Affairs code
    geometry         geometry(MultiPolygon, 4326) NOT NULL
)"""

LOAD_KABUPATEN = """
INSERT INTO ref.kabupaten (code, name, type, province_code, code_kemendagri, geometry)
SELECT code, name, type, province_code, code_kemendagri,
       CASE WHEN ST_IsValid(geometry) THEN ST_Multi(geometry)
            ELSE ST_Multi(ST_CollectionExtract(ST_MakeValid(geometry), 3)) END
FROM raw.boundary_kabupaten
WHERE code <> '0'"""

with connect() as conn:
    if conn.execute("SELECT to_regclass('ref.kabupaten')").fetchone()[0]:
        print("ref.kabupaten already exists: left as it is")
    else:
        conn.execute(KABUPATEN_DDL)
        n = conn.execute(LOAD_KABUPATEN).rowcount
        conn.execute("CREATE INDEX kabupaten_geometry_gist ON ref.kabupaten USING gist (geometry)")
        conn.execute("COMMENT ON TABLE ref.kabupaten IS 'Kabupaten/kota of Java: BIG 2022 boundaries with BPS "
                     "and Kemendagri codes (ledger L139), loaded by Chapter 3'")
        conn.execute("ANALYZE ref.kabupaten")
        print(f"ref.kabupaten: {n} rows inserted")
ref.kabupaten: 119 rows inserted

Now the provinces. Rather than loading a second file, the next cell dissolves the kabupaten/kota of each province into one shape: ST_Union is an aggregate, like sum, so with GROUP BY province_code it merges all shapes of a province and removes the shared borders. In the source data each province is the union of all its pieces (ledger L139); because the two unnamed pieces are left out, Jawa Timur comes out about 98 ha smaller than in the source (ledger L144).

PROVINCE_DDL = """
CREATE TABLE ref.province (
    code      char(2)  PRIMARY KEY,                 -- BPS province code, 31 to 36 in Java
    name      text     NOT NULL,
    geometry  geometry(MultiPolygon, 4326) NOT NULL
)"""

LOAD_PROVINCE = """
INSERT INTO ref.province (code, name, geometry)
SELECT k.province_code, p.province_name, ST_Multi(ST_Union(k.geometry))
FROM ref.kabupaten k
JOIN (SELECT DISTINCT province_code, province_name FROM raw.boundary_kabupaten) p USING (province_code)
GROUP BY k.province_code, p.province_name"""

with connect() as conn:
    if conn.execute("SELECT to_regclass('ref.province')").fetchone()[0]:
        print("ref.province already exists: left as it is")
    else:
        t = time.perf_counter()
        conn.execute(PROVINCE_DDL)
        n = conn.execute(LOAD_PROVINCE).rowcount
        conn.execute("CREATE INDEX province_geometry_gist ON ref.province USING gist (geometry)")
        conn.execute("COMMENT ON TABLE ref.province IS 'Provinces of Java: union of ref.kabupaten, built by Chapter 3'")
        conn.execute("ANALYZE ref.province")
        print(f"ref.province: {n} rows in {time.perf_counter() - t:.0f} s")
ref.province: 6 rows in 9 s

A foreign key ties every kabupaten/kota to an existing province: PostgreSQL then refuses a province code in ref.kabupaten that ref.province does not have. The cell adds it only if ref.kabupaten has none yet; the system table pg_constraint lists a table’s constraints (contype = 'f' marks foreign keys).

with connect() as conn:
    has_fk = conn.execute("""SELECT count(*) FROM pg_constraint
                             WHERE conrelid = 'ref.kabupaten'::regclass AND contype = 'f'""").fetchone()[0]
    if has_fk:
        print("ref.kabupaten already has its foreign key")
    else:
        conn.execute("ALTER TABLE ref.kabupaten ADD FOREIGN KEY (province_code) REFERENCES ref.province (code)")
        print("foreign key added: ref.kabupaten.province_code -> ref.province.code")
foreign key added: ref.kabupaten.province_code -> ref.province.code

Look before moving on. Three checks: counts per province, areas, and validity. Areas come from geography, on the spheroid, in hectares. The provinces should have the same area as their kabupaten/kota together, up to rounding, because one was made from the other.

The query introduces SQL tools used through the series. count(*) FILTER (WHERE ...) counts only the rows that meet a condition, so one pass gives several counts; bool_and is true when a condition holds for every row of a group; ILIKE is a case-insensitive LIKE. The kabupaten/kota are aggregated per province first and then joined to the provinces, so each province’s large shape is measured once.

SUMMARY = """
SELECT p.code, p.name, k.kabupaten_kota, k.of_which_kota, k.kabupaten_ha,
       round(ST_Area(p.geometry::geography) / 1e4)  AS province_ha,
       k.all_valid
FROM ref.province p
JOIN (SELECT province_code,
             count(*)                                          AS kabupaten_kota,
             count(*) FILTER (WHERE type ILIKE 'kota%')        AS of_which_kota,
             round(sum(ST_Area(geometry::geography)) / 1e4)    AS kabupaten_ha,
             bool_and(ST_IsValid(geometry))                    AS all_valid
      FROM ref.kabupaten GROUP BY province_code) k ON k.province_code = p.code
ORDER BY p.code"""

with connect() as conn:
    summary = pd.DataFrame(conn.execute(SUMMARY).fetchall(),
                           columns=["code", "name", "kabupaten_kota", "of_which_kota", "kabupaten_ha", "province_ha", "all_valid"])
summary
code name kabupaten_kota of_which_kota kabupaten_ha province_ha all_valid
0 31 DKI Jakarta 6 5 66098.0 66098.0 True
1 32 Jawa Barat 27 9 3704486.0 3704486.0 True
2 33 Jawa Tengah 35 6 3433749.0 3433749.0 True
3 34 Daerah Istimewa Yogyakarta 5 1 317065.0 317065.0 True
4 35 Jawa Timur 38 9 4803684.0 4803684.0 True
5 36 Banten 8 4 935277.0 935277.0 True

A point whose kabupaten you know is the second check: 110 E, 7 S lies in Kab. Batang (ledger L134). EXPLAIN shows how PostgreSQL runs the query without changing anything: with the GiST index, it first finds the shapes whose bounding boxes contain the point (&&), and runs the exact ST_Intersects test only on those.

POINT_QUERY = """SELECT code, name FROM ref.kabupaten
                 WHERE ST_Intersects(geometry, ST_SetSRID(ST_MakePoint(110, -7), 4326))"""
with connect() as conn:
    print("110 E, 7 S lies in:", conn.execute(POINT_QUERY).fetchall())
    for (line,) in conn.execute("EXPLAIN " + POINT_QUERY):
        print("  ", line)
110 E, 7 S lies in: [('3325', 'Batang')]
   Index Scan using kabupaten_geometry_gist on kabupaten  (cost=0.14..20.65 rows=1 width=15)
     Index Cond: (geometry && '0101000020E61000000000000000805B400000000000001CC0'::geometry)
     Filter: st_intersects(geometry, '0101000020E61000000000000000805B400000000000001CC0'::geometry)

A map is a quick check that nothing is missing or misplaced. For drawing only, the query simplifies the shapes with ST_CoverageSimplify, which drops vertices closer than 0.005 degree (about 550 m here, ledger L146) to the simplified line. Unlike simplifying each shape on its own, it treats the kabupaten/kota as one coverage, so neighbours keep a shared border without gaps; OVER () makes it a window function over all rows at once. The cell prints how much smaller the drawing data is.

DRAW_KAB = """SELECT code, province_code, ST_CoverageSimplify(geometry, 0.005) OVER () AS geometry FROM ref.kabupaten"""
DRAW_PROV = """SELECT code, name, ST_CoverageSimplify(geometry, 0.005) OVER () AS geometry FROM ref.province"""
k_draw = gpd.read_postgis(DRAW_KAB, ENGINE, geom_col="geometry")
p_draw = gpd.read_postgis(DRAW_PROV, ENGINE, geom_col="geometry")
with connect() as conn:
    n_full, mb_full = conn.execute("SELECT sum(ST_NPoints(geometry)), sum(length(ST_AsBinary(geometry))) / 1e6 "
                                   "FROM ref.kabupaten").fetchone()
print(f"kabupaten/kota vertices: {n_full:,} in the database ({mb_full:.1f} MB), "
      f"{int(k_draw.count_coordinates().sum()):,} drawn")

fig, ax = plt.subplots(figsize=(10, 3.6))
k_draw.plot(ax=ax, column="province_code", categorical=True, cmap="Pastel1", edgecolor="0.55", linewidth=0.3)
p_draw.boundary.plot(ax=ax, color="0.15", linewidth=0.8)
for _, r in p_draw.iterrows():
    pt = r.geometry.representative_point()
    ax.annotate(r["name"], (pt.x, pt.y), ha="center", fontsize=7)
ax.plot(110, -7, "k^", markersize=5)
ax.set_title(f"Java: {len(k_draw)} kabupaten/kota (thin lines) in {len(p_draw)} provinces (thick lines); "
             "triangle: 110 E, 7 S")
ax.set_axis_off()
plt.show()
kabupaten/kota vertices: 2,900,220 in the database (46.4 MB), 16,731 drawn

Map of Java's 119 kabupaten/kota coloured by province, with the six province borders drawn thicker and a triangle at 110 E, 7 S inside Jawa Tengah.

Look before moving on. A right map shows Java from Banten in the west to Jawa Timur in the east, with Madura and the smaller islands of Jawa Timur in that province, the Kepulauan Seribu islands as specks north of Jakarta, no gaps between neighbours, and the triangle inside Jawa Tengah.

5. Where the two code systems differ

The next query lists the kabupaten/kota whose BPS and Kemendagri codes differ. If you joined the damage reports on the wrong code, these rows would get another city’s numbers without any error.

with connect() as conn:
    differ = conn.execute("""SELECT code AS bps, code_kemendagri, name FROM ref.kabupaten
                             WHERE code <> code_kemendagri ORDER BY code""").fetchall()
pd.DataFrame(differ, columns=["bps", "kemendagri", "name"])
bps kemendagri name
0 3171 3174 Kota Administrasi Jakarta Selatan
1 3172 3175 Kota Administrasi Jakarta Timur
2 3173 3171 Kota Administrasi Jakarta Pusat
3 3174 3173 Kota Administrasi Jakarta Barat
4 3175 3172 Kota Administrasi Jakarta Utara

The five cities of DKI Jakarta carry the same set of codes in both systems, assigned in a different order (ledger L25). Elsewhere in Java the two codes are equal, so a join on the wrong code would look right for 114 regions and silently swap these five.

For another part of Indonesia, start from BIG’s layer (ledger L137) and take the BPS codes from the BPS relation table (ledger L138). Kecamatan are left out of this series: BIG’s kecamatan layer carries no BPS code (ledger L142), and no later chapter needs them.

6. The damage reports

The Ministry of Agriculture (Kementerian Pertanian) publishes monthly damage reports on its non-commodity database, datanonkom, on the page “Data Iklim Pertanian”, https://datanonkom.pertanian.go.id/master/iklim/data (ledger L1). It has two topics: DPI, the impact of climate change, which is flood and drought damage (banjir and kekeringan) to rice (padi), maize (jagung) and soybean (kedelai), and OPT, damage by the main pests (ledger L1). Each value is an area in hectares per kabupaten/kota and month, in two classes: terkena (affected) and puso (crop failure) (ledger L1). Month 13 on the page is the year total, Setahun. These are reports compiled by the ministry; how they are collected is not described on the page, and the series treats them as one independent signal of loss, with their own errors.

Open the page in your browser before going on: choose a topic, a few years and Kabupaten/Kota, look at the table, and watch the address bar. Every choice in the form becomes a parameter in the URL; section 9 builds the same URLs in Python.

Three facts decide how this chapter collects the data:

  • the data table is part of the HTML page itself; there is no separate data request to reuse (ledger L9);
  • the page has an export link, but the site’s robots.txt disallows it for automated tools, while it allows the data page (ledger L3, ledger L145);
  • no licence or terms of use appear on the data page (ledger L7).

So the chapter reads the HTML page, slowly, keeps every response in a cache so that no page is requested twice, and stores the result only in your own database. This chapter shows one kabupaten’s values and Java totals to teach the checks; do not publish the collected table itself until its terms of use are known.

7. Ask first: robots.txt

A site’s robots.txt says which paths automated clients may fetch. RFC 9309, the standard for it, lets a rule contain * (any characters), and when several rules match a path the longest one wins. It also lets a client keep a copy for up to 24 hours (ledger L140).

Web servers answer every request with a status code: 200 means OK, 4xx codes (404 not found, 403 forbidden, 429 too many requests) mean the request was refused, and 5xx codes mean the server failed. RFC 9309 says that if robots.txt answers with a 5xx code, a client must assume everything is disallowed (ledger L140). The function below stops on any error, which is stricter.

robot_rules reads the rules with Python’s urllib.robotparser, fetching robots.txt again only when the saved copy is older than max_age_h hours. This cell shows the saved copy if there is one; the fetcher in section 8 checks again, with the 24-hour limit, before each request it actually sends. A run that finds every page in the cache therefore works offline.

SITE = "https://datanonkom.pertanian.go.id"
URL_DATA = SITE + "/master/iklim/data"
EXPORT = SITE + "/master/iklim/data/export"        # where the page's export link points (ledger L145)
USER_AGENT = ("Mozilla/5.0 (compatible; postgis-crop-insurance tutorial; "
              "https://github.com/osgeoid/postgis-crop-insurance; one request at a time)")
DNK = DATA / "datanonkom" / "java"                 # this chapter's cache of web pages
ROBOTS_FILE = DNK / "robots.txt"


def robot_rules(max_age_h=24):
    """The site's robots.txt rules; fetched again if the saved copy is older than max_age_h (None: any age)."""
    fresh = ROBOTS_FILE.exists() and (max_age_h is None or time.time() - ROBOTS_FILE.stat().st_mtime < max_age_h * 3600)
    if not fresh:
        r = requests.get(SITE + "/robots.txt", headers={"User-Agent": USER_AGENT}, timeout=60)
        r.raise_for_status()                      # any error (4xx, 5xx): stop
        ROBOTS_FILE.parent.mkdir(parents=True, exist_ok=True)
        ROBOTS_FILE.write_text(r.text, encoding="utf-8")
    rp = robotparser.RobotFileParser()
    rp.parse(ROBOTS_FILE.read_text(encoding="utf-8").splitlines())
    if not rp.can_fetch(USER_AGENT, URL_DATA):
        raise RuntimeError("robots.txt does not allow the data page: stop here")
    if rp.can_fetch(USER_AGENT, EXPORT):
        raise RuntimeError("this parser allows the export path that the rule /*/export disallows: "
                           "it does not follow RFC 9309's wildcards")
    return rp


rp = robot_rules(max_age_h=None)
saved = dt.datetime.fromtimestamp(ROBOTS_FILE.stat().st_mtime).isoformat(timespec="minutes")
print(f"robots.txt saved {saved}:\n")
print(ROBOTS_FILE.read_text(encoding="utf-8").strip(), "\n")
for p in [URL_DATA, EXPORT]:
    print(f"{p:60s}", "allowed" if rp.can_fetch(USER_AGENT, p) else "disallowed")
robots.txt saved 2026-12-01T13:49:

User-agent: *
Allow: /
Disallow: /login
Disallow: /logout
Disallow: /api/
Disallow: /admin
Disallow: /*/export
Disallow: /cari/

Sitemap: https://datanonkom.pertanian.go.id/sitemap.xml 

https://datanonkom.pertanian.go.id/master/iklim/data         allowed
https://datanonkom.pertanian.go.id/master/iklim/data/export  disallowed

Look before moving on. The data page matches only Allow: /, so it is allowed. The export path matches Allow: / and also Disallow: /*/export, where * stands for master/iklim/data; the disallow rule is longer, so it wins. Python’s documentation does not say whether robotparser handles * (ledger L140), which is why robot_rules tests the export path instead of trusting the parser. There is no Crawl-delay line, so the pause between requests below is this series’ choice, not the site’s rule.

8. A polite fetcher

Every page request in this chapter goes through one function, fetch. It

  • looks in the cache first. The cache key is a fingerprint of the request’s parameters, so the same question is never sent twice. Each page is stored compressed, next to a small JSON file with the URL, the time of access in UTC, the HTTP status and the size;
  • checks robots.txt (section 7) before going to the network;
  • waits DELAY_S seconds after each answer before the next request, and sends one request at a time;
  • names itself in the User-Agent header, with a link to this tutorial, so the site’s operators can see what it is. “Mozilla/5.0 (compatible; …)” is the usual form for automated clients;
  • on 429 (too many requests) or a 5xx server error, waits (as long as the server’s Retry-After header asks, if it sends one) and tries again, up to five attempts in all;
  • stops on 403 (forbidden): the site is refusing automated requests (it is served through Cloudflare, a service in front of the site that can block automated traffic, ledger L9), and the polite answer is to stop, not to work around it;
  • refuses to cache an answer that is not the data page, such as a challenge or maintenance page, so a bad answer cannot spoil later runs.

STATE counts the requests sent and the pages read from the cache.

DELAY_S = 5
CACHE = DNK / "raw"
STATE = {"sent": 0, "cached": 0, "last": 0.0}      # a dict, so that fetch() can update it
SESSION = requests.Session()
SESSION.headers["User-Agent"] = USER_AGENT


def fetch(params: list) -> tuple:
    """GET the data page with these parameters, from the cache if possible. Returns (bytes, info)."""
    key = hashlib.sha1(json.dumps(params).encode()).hexdigest()[:16]
    body, meta = CACHE / f"{key}.html.gz", CACHE / f"{key}.json"
    if body.exists() and meta.exists():
        STATE["cached"] += 1
        return gzip.decompress(body.read_bytes()), json.loads(meta.read_text(encoding="utf-8"))
    robot_rules(max_age_h=24)                       # before any request to the site
    CACHE.mkdir(parents=True, exist_ok=True)
    for attempt in range(1, 6):
        time.sleep(max(0.0, DELAY_S - (time.time() - STATE["last"])))
        STATE["sent"] += 1
        try:
            r = SESSION.get(URL_DATA, params=params, timeout=180)
        except requests.RequestException as e:
            print(f"  network error ({e.__class__.__name__}), attempt {attempt}")
            if attempt < 5:
                time.sleep(30 * attempt)
            continue
        finally:
            STATE["last"] = time.time()             # the pause counts from the end of the answer
        if r.status_code == 403:
            raise RuntimeError("HTTP 403: the site is refusing automated requests. Stop and try another day.")
        if r.status_code == 429 or r.status_code >= 500:
            retry_after = r.headers.get("Retry-After", "")
            wait = int(retry_after) if retry_after.isdigit() else 60 * attempt
            print(f"  HTTP {r.status_code}, attempt {attempt}" + (f", waiting {wait} s" if attempt < 5 else ""))
            if attempt < 5:
                time.sleep(wait)
            continue
        r.raise_for_status()
        if b"<main" not in r.content or b"Data update per tanggal" not in r.content:
            raise RuntimeError("the answer is not the data page (a challenge or maintenance page?); not cached")
        info = {"url": r.url, "accessed_utc": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
                "status": r.status_code, "bytes": len(r.content)}
        body.write_bytes(gzip.compress(r.content))
        meta.write_text(json.dumps(info, indent=1), encoding="utf-8")
        return r.content, info
    raise RuntimeError(f"no answer after 5 attempts: {params[:4]}")

9. One kabupaten first

The page’s form becomes URL parameters: the topic (topik), the table view (tampilan=2, which also adds an INDONESIA total row, ledger L5), the level (vertikal=3, kabupaten/kota), a name search (q), and lists of years, variables, classes and months (ledger L1). One request may ask for many of each, and the table repeats its columns for every combination (ledger L5). So one request per region and topic, with every year the form offers (2002 to 2026), every variable, both classes and all 13 months, collects that region’s whole record.

The parameters are a list of pairs rather than a dictionary because names such as tahun[] (year) repeat: requests turns each pair into one name=value in the URL.

The search q matches parts of region names, not codes (ledger L4, ledger L145), and the table shows at most 200 regions (ledger L4). search_term strips “Kota” and “Kabupaten” from a name, so “Kota Blitar” searches for “Blitar”, which finds Kab. Blitar and Kota Blitar at once.

Start with one region, Kab. Indramayu in Jawa Barat, and the DPI topic. On a first run this sends one request; afterwards the page comes from the cache.

YEARS = list(range(2002, 2027))                     # the years the form offers (ledger L1)
TOPICS = {                                         # topik id and its variables, as labelled on the page
    "dpi": (3, {8: "Banjir Padi", 9: "Banjir Jagung", 10: "Banjir Kedelai",
                11: "Kekeringan Padi", 12: "Kekeringan Jagung", 13: "Kekeringan Kedelai"}),
    "opt": (2, {5: "Padi", 6: "Jagung", 7: "Kedelai"}),
}
KLAS = {2: "Terkena", 3: "Puso"}
MONTHS = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September",
          "Oktober", "November", "Desember", "Setahun"]


def search_term(name: str) -> str:
    """'Kota Blitar' -> 'Blitar': the part of a name the site's search matches."""
    return re.sub(r"^(Kabupaten|Kab\.|Kota Administrasi|Kota Adm\.|Kota|Administrasi)\s+", "", name.strip(),
                  flags=re.I).strip()


def params_for(topic: str, term: str) -> list:
    topik, variables = TOPICS[topic]
    return ([("topik", topik), ("tampilan", 2), ("vertikal", 3), ("q", term)]
            + [("tahun[]", y) for y in YEARS] + [("variabel[]", v) for v in variables]
            + [("klasifikasi[]", k) for k in KLAS] + [("bulan[]", m) for m in range(1, 14)])


content, info = fetch(params_for("dpi", "Indramayu"))
print(info["url"][:170], "...")
print(f"{info['bytes'] / 1e6:.1f} MB of HTML, accessed {info['accessed_utc']} (UTC)")
print("requests sent:", STATE["sent"], "| read from cache:", STATE["cached"])
https://datanonkom.pertanian.go.id/master/iklim/data?topik=3&tampilan=2&vertikal=3&q=Indramayu&tahun%5B%5D=2002&tahun%5B%5D=2003&tahun%5B%5D=2004&tahun%5B%5D=2005&tahun%5 ...
3.2 MB of HTML, accessed 2026-11-30T10:30:09+00:00 (UTC)
requests sent: 0 | read from cache: 1

An HTML table is a <table> element with a header part, <thead>, and a body, <tbody>. Both hold rows, <tr>, made of cells, <th> or <td>. A cell with colspan="26" stretches over 26 columns below it. BeautifulSoup reads the HTML into a tree that Python can search; on this site the data table sits inside the page’s <main> element.

This table has four header rows: variable, year, month and class. The cell below expands every header row to one label per column and prints the first few, so you can read a column’s labels from top to bottom.

def cells_of(tr):
    return tr.find_all(["th", "td"], recursive=False)


def expand(cells) -> list:
    """One label per column: a cell with colspan=26 counts 26 times."""
    out = []
    for c in cells:
        out += [c.get_text(strip=True)] * int(c.get("colspan") or 1)
    return out


table = BeautifulSoup(content, "html.parser").find("main").find("table")
head = table.find("thead").find_all("tr", recursive=False)
print(len(head), "header rows; the first starts with", [c.get_text(strip=True) for c in cells_of(head[0])[:2]])
labels = [expand(cells_of(head[0])[2:])] + [expand(cells_of(h)) for h in head[1:]]
for name, row in zip(["variable", "year", "month", "class"], labels):
    print(f"{name:9s} {len(row):5d} columns: {row[:4]} ...")
4 header rows; the first starts with ['Kode', 'Wilayah']
variable   3900 columns: ['Banjir Padi', 'Banjir Padi', 'Banjir Padi', 'Banjir Padi'] ...
year       3900 columns: ['2002', '2002', '2002', '2002'] ...
month      3900 columns: ['Januari', 'Januari', 'Februari', 'Februari'] ...
class      3900 columns: ['Terkena', 'Puso', 'Terkena', 'Puso'] ...

Column 1 is therefore Banjir Padi, 2002, Januari, Terkena; column 2 the same with Puso; and so on. Each body row is one region: its code, its name, then one value per column. On the page, “-” means no record, and “0.00” means zero hectares or a month not reported yet (section 12). parse turns “-” into None, which becomes NULL in the database, and skips the INDONESIA total row. It also reads the date the page prints after “Data update per tanggal”; that date depends on the years requested (ledger L2), and every request here includes 2026.

def parse(content: bytes, topic: str) -> tuple:
    """Return (rows, update date as printed). rows: (code, name, variabel_id, year, month, klas_id, ha or None)."""
    main = BeautifulSoup(content, "html.parser").find("main")
    m = re.search(r"Data update per tanggal\s+(\d{1,2}\s+\w+\s+\d{4})", main.get_text(" ") if main else "")
    update = m.group(1) if m else ""
    table = main.find("table") if main else None
    if table is None:
        return [], update                             # no region matched the search
    head = table.find("thead").find_all("tr", recursive=False)
    if len(head) != 4:
        raise ValueError(f"expected 4 header rows, found {len(head)}: the page layout has changed")
    var_row = expand(cells_of(head[0])[2:])           # the first two cells are Kode and Wilayah
    year_row, month_row, klas_row = (expand(cells_of(h)) for h in head[1:])
    if not len(var_row) == len(year_row) == len(month_row) == len(klas_row):
        raise ValueError("header rows of different widths: the page layout has changed")
    by_label = {v: k for k, v in TOPICS[topic][1].items()}
    klas_id = {v: k for k, v in KLAS.items()}
    cols = [(by_label[v], int(y), MONTHS.index(mo) + 1, klas_id[k])
            for v, y, mo, k in zip(var_row, year_row, month_row, klas_row)]
    rows = []
    for tr in table.find("tbody").find_all("tr", recursive=False):
        cells = [c.get_text(strip=True) for c in cells_of(tr)]
        code, name, values = cells[0], cells[1], cells[2:]
        if code == "-" or name == "INDONESIA":        # the total row of this view (ledger L5)
            continue
        if len(values) != len(cols):
            raise ValueError(f"{code} {name}: {len(values)} values for {len(cols)} columns")
        for (v, y, mo, k), raw in zip(cols, values):
            rows.append((code, name, v, y, mo, k, None if raw in ("-", "") else float(raw.replace(",", ""))))
    return rows, update


rows, update = parse(content, "dpi")
one_region = pd.DataFrame(rows, columns=["code", "name", "variabel_id", "year", "month", "klasifikasi_id", "ha"])
print("data update per", update, "|", len(one_region), "values for", ", ".join(one_region.name.unique()))
(one_region.query("variabel_id == 11 and month == 13 and year in [2015, 2019, 2020, 2023, 2025]")
    .pivot(index="year", columns="klasifikasi_id", values="ha").rename(columns=KLAS))
data update per 27 November 2026 | 3900 values for Kab. Indramayu
klasifikasi_id Terkena Puso
year
2015 NaN NaN
2019 20136.5 13653.0
2020 2085.0 566.0
2023 9762.0 3018.0
2025 173.0 0.0

Look before moving on. One region and one topic give 25 years x 6 variables x 13 months x 2 classes = 3,900 values. The table is Kekeringan Padi (drought, rice), Setahun, for Kab. Indramayu. Compare it with the values read in a browser on the day of collection (ledger L6): no record in 2015, and terkena / puso of 20,136.50 / 13,653.00 ha in 2019, 2,085.00 / 566.00 in 2020, 9,762.00 / 3,018.00 in 2023 and 173.00 / 0.00 in 2025. You can check them yourself with the URL in ledger L6. Your numbers can differ if the ministry has revised its reports since; the access time printed above tells you which version you have.

10. All of Java

The loop below runs the same request for every search term and both topics: about 200 pages. With an empty cache this takes a while. The author’s scrape of the same 200 pages, with scripts/scrape_datanonkom.py and the same 5-second pause counted from the start of each request, took 23 minutes for 536 MB of HTML (ledger L141); fetch pauses after each answer, so expect somewhat longer. A progress line appears every 10 pages. Interrupting and rerunning the cell is safe: saved pages are not requested again.

A search can find regions outside Java with a similar name, so rows are kept only for codes in ref.kabupaten, and each region and topic is taken from the first search that found it. Two columns are added to every value: after_update, true for months that start after the page’s update date (and for that year’s Setahun total, which is partial), and the access time of the page.

If raw.datanonkom_damage already exists, the cell skips the loop, since the next cell would not load the rows anyway.

def update_date(text: str):
    """'27 November 2026' -> date(2026, 11, 27), or None."""
    m = re.fullmatch(r"(\d{1,2})\s+(\w+)\s+(\d{4})", text.strip())
    if not m or m.group(2).capitalize() not in MONTHS[:12]:
        return None
    return dt.date(int(m.group(3)), MONTHS.index(m.group(2).capitalize()) + 1, int(m.group(1)))


def after_update(year: int, month: int, updated) -> bool:
    if updated is None:
        return False
    return year >= updated.year if month == 13 else dt.date(year, month, 1) > updated


with connect() as conn:
    loaded = conn.execute("SELECT to_regclass('raw.datanonkom_damage')").fetchone()[0]
    regions = dict(conn.execute("SELECT code, name FROM ref.kabupaten").fetchall())
terms = sorted({search_term(n) for n in regions.values()})
print(len(regions), "regions,", len(terms), "search terms,", len(terms) * len(TOPICS), "pages")

records = None
if loaded:
    print("raw.datanonkom_damage already exists: pages not read again")
else:
    records, found, outside, t = [], {}, set(), time.perf_counter()
    for topic, (topik, variables) in TOPICS.items():
        for i, term in enumerate(terms, 1):
            content, info = fetch(params_for(topic, term))
            rows, update = parse(content, topic)
            updated = update_date(update)
            for code, name, v, y, mo, k, ha in rows:
                if code not in regions:               # a region outside Java with a similar name
                    outside.add(code)
                    continue
                first_term = found.setdefault((code, topik), term)
                if first_term != term:                # this region and topic came from another search already
                    continue
                records.append((code, name, topik, v, variables[v], y, mo, k, KLAS[k], ha,
                                after_update(y, mo, updated), update, info["accessed_utc"]))
            if i % 10 == 0 or i == len(terms):
                print(f"{topic} {i}/{len(terms)} | sent {STATE['sent']} | cached {STATE['cached']} | "
                      f"{time.perf_counter() - t:.0f} s")
    missing = sorted({(c, tp) for c in regions for tp in (2, 3)} - set(found))
    print(f"{len(records):,} values | regions found per topic:",
          {tp: sum(1 for c, x in found if x == tp) for tp in (2, 3)},
          f"| codes outside Java skipped: {len(outside)} | missing: {missing}")
    assert not missing, f"regions not found on the site: {missing}"
119 regions, 100 search terms, 200 pages
dpi 10/100 | sent 0 | cached 11 | 16 s
dpi 20/100 | sent 0 | cached 21 | 29 s
dpi 30/100 | sent 0 | cached 31 | 40 s
dpi 40/100 | sent 0 | cached 41 | 52 s
dpi 50/100 | sent 0 | cached 51 | 64 s
dpi 60/100 | sent 0 | cached 61 | 78 s
dpi 70/100 | sent 0 | cached 71 | 91 s
dpi 80/100 | sent 0 | cached 81 | 103 s
dpi 90/100 | sent 0 | cached 91 | 116 s
dpi 100/100 | sent 0 | cached 101 | 129 s
opt 10/100 | sent 0 | cached 111 | 138 s
opt 20/100 | sent 0 | cached 121 | 146 s
opt 30/100 | sent 0 | cached 131 | 152 s
opt 40/100 | sent 0 | cached 141 | 159 s
opt 50/100 | sent 0 | cached 151 | 166 s
opt 60/100 | sent 0 | cached 161 | 174 s
opt 70/100 | sent 0 | cached 171 | 182 s
opt 80/100 | sent 0 | cached 181 | 189 s
opt 90/100 | sent 0 | cached 191 | 196 s
opt 100/100 | sent 0 | cached 201 | 203 s
696,150 values | regions found per topic: {2: 119, 3: 119} | codes outside Java skipped: 8 | missing: []

Look before moving on. A right result finds all 119 regions for both topics, with nothing missing. Each region has 3,900 DPI values (section 9) and 1,950 OPT values (3 variables instead of 6), 5,850 in all, so Java gives 119 x 5,850 = 696,150 values. On a run with a full cache, sent stays 0.

11. Into the database

The table keeps the data as received: one row per region, topic, variable, year, month and class. Its design does the checking:

  • the primary key over those six columns rejects a duplicate value;
  • the foreign key on code refers to ref.kabupaten: the loop already kept only codes in that table, and the foreign key makes sure no later insert can add a region that is not one of the 119;
  • CHECK constraints keep the ids to the values the page uses (ledger L1), months in 1 to 13 and areas at zero or above;
  • ha may be NULL, for “-” on the page.

COPY is PostgreSQL’s bulk loader, which the PostgreSQL manual recommends over many single INSERTs for loading many rows (Populating a database); psycopg feeds it row by row from Python and turns None into NULL.

DAMAGE_DDL = """
CREATE TABLE raw.datanonkom_damage (
    code            char(4)   NOT NULL REFERENCES ref.kabupaten (code),
    name            text      NOT NULL,
    topik           smallint  NOT NULL CHECK (topik IN (2, 3)),            -- 2 OPT (pests), 3 DPI (flood, drought)
    variabel_id     smallint  NOT NULL CHECK (variabel_id BETWEEN 5 AND 13),
    variabel        text      NOT NULL,
    year            smallint  NOT NULL CHECK (year BETWEEN 2002 AND 2100),
    month           smallint  NOT NULL CHECK (month BETWEEN 1 AND 13),     -- 13 = Setahun (year total)
    klasifikasi_id  smallint  NOT NULL CHECK (klasifikasi_id IN (2, 3)),   -- 2 Terkena (affected), 3 Puso (crop failure)
    klasifikasi     text      NOT NULL,
    ha              numeric(12, 2) CHECK (ha >= 0),   -- NULL = "-" on the page: no record
    after_update    boolean   NOT NULL,               -- month starts after the page's update date
    source_update   text,                             -- "Data update per tanggal", as printed
    accessed_utc    timestamptz NOT NULL,
    PRIMARY KEY (code, topik, variabel_id, year, month, klasifikasi_id)
)"""
COPY_DAMAGE = ("COPY raw.datanonkom_damage (code, name, topik, variabel_id, variabel, year, month, klasifikasi_id, "
               "klasifikasi, ha, after_update, source_update, accessed_utc) FROM STDIN")

if records is None:
    print("raw.datanonkom_damage already exists: left as it is")
else:
    with connect() as conn:
        t = time.perf_counter()
        conn.execute(DAMAGE_DDL)
        with conn.cursor().copy(COPY_DAMAGE) as cp:
            for rec in records:
                cp.write_row(rec)
        conn.execute("COMMENT ON TABLE raw.datanonkom_damage IS 'Scraped from "
                     "https://datanonkom.pertanian.go.id/master/iklim/data (HTML page) by Chapter 3; "
                     "ha NULL = no record on the page'")
        conn.execute("ANALYZE raw.datanonkom_damage")
        print(f"raw.datanonkom_damage: {len(records):,} rows in {time.perf_counter() - t:.0f} s")
raw.datanonkom_damage: 696,150 rows in 18 s

12. No record, zero, and not reported yet

Three different situations look alike in a careless table:

  • no record (“-”, NULL): the database has no value for that year at all;
  • zero (0.00): a report of no damaged area;
  • not reported yet: a month the ministry has not filled in, which the page also shows as 0.00.

If all three became 0, an average of damage over years would count years with no data as years without damage. The first query shows, per topic, which years have values and how the monthly cells split. (ha = 0)::int turns true and false into 1 and 0, so its average is the share of zeros.

COVERAGE = """
SELECT topik,
       min(year) FILTER (WHERE ha IS NOT NULL)        AS first_year_with_values,
       max(year) FILTER (WHERE ha IS NOT NULL)        AS last_year_with_values,
       max(year) FILTER (WHERE ha IS NULL)            AS last_year_without,
       count(*) FILTER (WHERE ha IS NULL)             AS no_record,
       count(*) FILTER (WHERE ha = 0)                 AS zero,
       count(*) FILTER (WHERE ha > 0)                 AS positive,
       round(avg((ha = 0)::int) FILTER (WHERE ha IS NOT NULL), 3) AS share_zero
FROM raw.datanonkom_damage
WHERE month <= 12
GROUP BY topik ORDER BY topik"""

with connect() as conn:
    cov = pd.DataFrame(conn.execute(COVERAGE).fetchall(),
                       columns=["topik", "first_year", "last_year", "last_year_no_record", "no_record", "zero",
                                "positive", "share_zero"])
cov
topik first_year last_year last_year_no_record no_record zero positive share_zero
0 2 2022 2026 2021 171360 32494 10346 0.758
1 3 2016 2026 2015 239904 179993 8503 0.955

Look before moving on. OPT (topik 2) has values from 2022 and DPI (topik 3) from 2016; every earlier year is NULL, for every region (ledger L18). So “-” marks the years before the database began, not a missing report, and an analysis of drought damage has the years from 2016 only. Within the years with values, most monthly cells are 0.00, about three quarters for pests and more than nine in ten for flood and drought (ledger L19): damage is reported in few months.

The next query looks at the end of the record: the update date the pages printed, and what the last months contain.

RECENT = """
SELECT source_update, year, month,
       count(*)                          AS cells,
       count(*) FILTER (WHERE ha = 0)    AS zero,
       count(*) FILTER (WHERE ha > 0)    AS positive,
       bool_and(after_update)            AS after_update
FROM raw.datanonkom_damage
WHERE year = (SELECT max(year) FROM raw.datanonkom_damage) AND month BETWEEN 9 AND 12
GROUP BY source_update, year, month ORDER BY month"""

with connect() as conn:
    recent = pd.DataFrame(conn.execute(RECENT).fetchall(),
                          columns=["source_update", "year", "month", "cells", "zero", "positive", "after_update"])
recent
source_update year month cells zero positive after_update
0 27 November 2026 2026 9 2142 1866 276 False
1 27 November 2026 2026 10 2142 1909 233 False
2 27 November 2026 2026 11 2142 1977 165 False
3 27 November 2026 2026 12 2142 2142 0 True

Look before moving on. The pages say they were updated on 27 November 2026. December 2026 is 0.00 in every cell, and after_update marks it: that is “not reported yet” in action, and without the flag those zeros would read as a month without damage. November 2026 contains the update date, so it is flagged false but may still be incomplete: the month, and the year, that contain the update date are partial. Chapter 11 treats seasons that end near this date as provisional.

Two more checks of the table against itself. Setahun should equal the sum of the twelve months. And puso (crop failure) is expected not to exceed terkena (affected) in the same month; the ministry’s own definitions of the two classes are not yet sourced in this series. The query uses a CTE (WITH m AS (...)), a named subquery, and joins the table to itself (USING (...) lists the columns both sides must share), so that terkena and puso of the same month sit on one row.

CHECKS = """
WITH m AS (
    SELECT code, topik, variabel_id, year, klasifikasi_id,
           sum(ha) FILTER (WHERE month <= 12)  AS months,
           max(ha) FILTER (WHERE month = 13)   AS setahun
    FROM raw.datanonkom_damage
    GROUP BY code, topik, variabel_id, year, klasifikasi_id
)
SELECT count(*) FILTER (WHERE setahun IS NOT NULL)                 AS groups_with_values,
       count(*) FILTER (WHERE (setahun IS NULL) <> (months IS NULL)) AS one_side_missing,
       max(abs(setahun - months))::float8                          AS largest_difference_ha,
       (SELECT count(*)
        FROM raw.datanonkom_damage t
        JOIN raw.datanonkom_damage p USING (code, topik, variabel_id, year, month)
        WHERE t.klasifikasi_id = 2 AND p.klasifikasi_id = 3 AND t.month <= 12
          AND p.ha > t.ha)                                         AS months_puso_above_terkena,
       (SELECT count(*)
        FROM raw.datanonkom_damage t
        JOIN raw.datanonkom_damage p USING (code, topik, variabel_id, year, month)
        WHERE t.klasifikasi_id = 2 AND p.klasifikasi_id = 3 AND t.month <= 12
          AND t.ha IS NOT NULL AND p.ha IS NOT NULL)               AS months_with_both
FROM m"""

with connect() as conn:
    checks = dict(zip(["groups_with_values", "one_side_missing", "largest_difference_ha",
                       "months_puso_above_terkena", "months_with_both"], conn.execute(CHECKS).fetchone()))
checks
{'groups_with_values': 19278,
 'one_side_missing': 0,
 'largest_difference_ha': 0.02,
 'months_puso_above_terkena': 18,
 'months_with_both': 115668}

Look before moving on. A group is one region, variable, class and year. In every group with values, Setahun and the months are either both present or both missing (one_side_missing 0), and they agree within a few hundredths of a hectare, the rounding of two-decimal values (ledger L20). Puso exceeds terkena in only a handful of the months that have both. The series keeps these values as published and checks the windows it uses in Chapter 11.

Finally, a first look at what Chapter 11 will use: rice area affected by drought and by flood in Java, per year, from the monthly values. HAVING count(ha) > 0 keeps only years with at least one value, so the no-record years before 2016 drop out.

YEARLY = """
SELECT year,
       round(sum(ha) FILTER (WHERE variabel_id = 11 AND klasifikasi_id = 2))::bigint AS drought_terkena_ha,
       round(sum(ha) FILTER (WHERE variabel_id = 11 AND klasifikasi_id = 3))::bigint AS drought_puso_ha,
       round(sum(ha) FILTER (WHERE variabel_id = 8  AND klasifikasi_id = 2))::bigint AS flood_terkena_ha,
       round(sum(ha) FILTER (WHERE variabel_id = 8  AND klasifikasi_id = 3))::bigint AS flood_puso_ha
FROM raw.datanonkom_damage
WHERE topik = 3 AND month <= 12
GROUP BY year HAVING count(ha) > 0
ORDER BY year"""

with connect() as conn:
    yearly = pd.DataFrame(conn.execute(YEARLY).fetchall(),
                          columns=["year", "drought_terkena_ha", "drought_puso_ha", "flood_terkena_ha", "flood_puso_ha"])
ax = yearly.set_index("year")[["drought_terkena_ha", "flood_terkena_ha"]].plot.bar(figsize=(9, 3), width=0.8)
ax.set_ylabel("rice area affected (ha)")
ax.set_title("Rice area affected (terkena) by drought and flood, Java, sum of monthly reports")
plt.show()
yearly

Bar chart of rice area affected by drought and by flood in Java per year from 2016 to 2026; drought varies much more from year to year than flood, and 2026 is partial.

year drought_terkena_ha drought_puso_ha flood_terkena_ha flood_puso_ha
0 2016 31470 3097 120698 25930
1 2017 14565 1537 82868 14502
2 2018 119838 22085 42416 7233
3 2019 227517 80216 51743 10486
4 2020 28160 5007 117476 27124
5 2021 38505 4167 113998 28108
6 2022 3212 2 63527 11787
7 2023 52961 10228 80838 41386
8 2024 100757 22011 95320 25289
9 2025 2280 26 93155 14937
10 2026 28088 4686 71530 13698

Look before moving on. Drought damage swings much more from year to year than flood damage, with a few large years. Those are the years a drought index should pay in; Chapter 11 tests whether it does. 2026, the year of the update date, is partial.

Checkpoint

The cell below checks, in a new session, what the next chapters rely on:

  • the 119 kabupaten/kota (ledger L8) with valid MultiPolygon geometries in EPSG:4326, a GiST index and a foreign key to the 6 provinces;
  • a damage table with a foreign key to ref.kabupaten, complete for every region (both topics, 5,850 values each: 25 years x 13 months x 2 classes x 9 variables), whose NULLs fill whole years only.

It depends only on the setup cell.

with connect() as conn:
    first_row = lambda q: conn.execute(q).fetchone()
    n_kab, n_valid, srids = first_row("SELECT count(*), count(*) FILTER (WHERE ST_IsValid(geometry)), "
                                      "array_agg(DISTINCT ST_SRID(geometry)) FROM ref.kabupaten")
    n_prov, n_prov_valid = first_row("SELECT count(*), count(*) FILTER (WHERE ST_IsValid(geometry)) FROM ref.province")
    types = dict(conn.execute("SELECT f_table_name, type || ' ' || srid FROM geometry_columns "
                              "WHERE f_table_schema = 'ref' AND f_table_name IN ('kabupaten', 'province')").fetchall())
    gist = first_row("SELECT count(*) FROM pg_indexes WHERE schemaname = 'ref' "
                     "AND tablename IN ('kabupaten', 'province') AND indexdef ILIKE '%USING gist%'")[0]
    fk_province = first_row("""SELECT count(*) FROM pg_constraint WHERE conrelid = 'ref.kabupaten'::regclass
                               AND contype = 'f' AND confrelid = 'ref.province'::regclass""")[0]
    fk_damage = first_row("""SELECT count(*) FROM pg_constraint WHERE conrelid = 'raw.datanonkom_damage'::regclass
                             AND contype = 'f' AND confrelid = 'ref.kabupaten'::regclass""")[0]
    n_rows, n_codes, per_min, per_max = first_row("SELECT sum(n), count(*), min(n), max(n) FROM "
                                                  "(SELECT code, count(*) AS n FROM raw.datanonkom_damage GROUP BY code) c")
    n_pairs = first_row("SELECT count(*) FROM (SELECT DISTINCT code, topik FROM raw.datanonkom_damage) p")[0]
    mixed = first_row("""SELECT count(*) FROM (
                             SELECT topik, variabel_id, year FROM raw.datanonkom_damage
                             GROUP BY topik, variabel_id, year
                             HAVING count(*) FILTER (WHERE ha IS NULL) > 0 AND count(ha) > 0) g""")[0]

assert n_kab == 119 and n_valid == 119 and srids == [4326], f"ref.kabupaten: {n_kab} rows, {n_valid} valid, SRIDs {srids}"
assert n_prov == 6 and n_prov_valid == 6, f"ref.province: {n_prov} rows, {n_prov_valid} valid"
assert types == {"kabupaten": "MULTIPOLYGON 4326", "province": "MULTIPOLYGON 4326"}, f"geometry columns: {types}"
assert gist == 2, "a GiST index is missing on ref.kabupaten or ref.province"
assert fk_province == 1, "ref.kabupaten has no foreign key to ref.province"
assert fk_damage == 1, "raw.datanonkom_damage has no foreign key to ref.kabupaten"
assert n_codes == 119 and per_min == per_max == 25 * 13 * 2 * 9, f"damage: {n_codes} regions, {per_min} to {per_max} values each"
assert n_pairs == 2 * 119, f"damage: {n_pairs} region-topic pairs, expected {2 * 119}"
assert mixed == 0, f"{mixed} variable-years mix NULL and values: a missing value inside the record"
print(f"checkpoint passed: {n_kab} kabupaten/kota, {n_prov} provinces, {n_rows:,} damage values "
      f"({per_min:,} per region); code cells took {time.perf_counter() - T0:.0f} s since the setup cell")
checkpoint passed: 119 kabupaten/kota, 6 provinces, 696,150 damage values (5,850 per region); code cells took 287 s since the setup cell

Troubleshooting

Symptom Cause Fix
data_dir is ..., on a drive this computer does not have config.yml still holds the author’s folder set data_dir to a folder on your computer, outside OneDrive or Dropbox
404 when downloading the boundary file the file is not at the URL in config.yml check boundaries.url against the repository’s releases page
checksum ... does not match config.yml the download was cut short, or the file was replaced delete the file in data_dir/boundaries and run the cell again
... already exists: left as it is, but you want to reload the cells never drop a table that later chapters may use before Chapter 4 builds on them, run with connect() as conn: conn.execute("DROP TABLE raw.datanonkom_damage, ref.kabupaten, ref.province") in a new cell, then run the chapter again
ConnectionError in section 7 or 8 no internet, and a page or a fresh robots.txt is needed go online; pages already saved are not requested again
robots.txt does not allow the data page the site has changed its rules stop: do not collect the data
this parser allows the export path ... your Python’s robotparser does not apply RFC 9309’s * rules fetch only requests the data page, which the rules allow; to be sure, read the printed rules yourself, then remove the export test from robot_rules
HTTP 403: the site is refusing automated requests the site’s protection blocks the script (ledger L9) stop and try another day; do not work around it. Chapters 4 to 10 do not need the damage table
the answer is not the data page the site sent a challenge or maintenance page wait and run again later; nothing was cached
expected 4 header rows or header rows of different widths the page layout has changed the parser needs updating; the pages already saved stay usable
regions not found on the site a region’s name on the site differs from the boundary file search the site for the region by hand and adjust search_term
your numbers differ from this page the ministry revises and extends its reports compare accessed_utc and source_update; both are stored with every value

Summary

You now have:

  • ref.kabupaten: Java’s 119 kabupaten/kota with BPS and Kemendagri codes, valid MultiPolygon geometries in EPSG:4326 and a GiST index. Chapter 5 and every later chapter key their tables on its code;
  • ref.province: the 6 provinces, built from the kabupaten/kota with ST_Union, used to group results by province;
  • raw.datanonkom_damage: monthly flood, drought and pest damage per kabupaten/kota as published, with “no record” as NULL, the page’s update date and the access time of every value. Chapter 11 compares payouts with it;
  • in data_dir: the boundary file and a compressed cache of every page requested, so a rerun sends no page requests;
  • raw.boundary_kabupaten: the boundary file as received, which nothing else uses.

What comes next

Chapter 4 loads daily rainfall for Java from 1981 to September 2026 (ledger L35) as rasters and adds it up to ten-day totals inside the database.

References