Skip to main content

Chapter 5: Paddy fields and insured units

Chapter 5: Paddy fields and insured units

TipAt a glance
  • You will build: ref.paddy_moa2015 (958,169 rice-field polygons of Java with irrigation class, kabupaten/kota and area) and idx.insured_unit (the kabupaten/kota with at least 1,000 ha of paddy)
  • You need: Chapters 2 and 3; an internet connection on the first run; two files (about 940 MB) to download into data_dir; about 2 GB of free memory; about 3 GB of space in the database
  • Time to run: About 13 minutes once the files are in data_dir (the checkpoint prints the time), most of it loading and joining in sections 4 and 5; the first run also downloads about 940 MB
  • Level: Intermediate

Rain matters to an insurer only where the insured crop grows. In this chapter you load nearly a million rice fields of Java (sawah, called paddy fields in this series), mapped by the Ministry of Agriculture, into the database: you move them from their own map projection to longitude and latitude, repair the shapes that are invalid, measure their areas on the spheroid, and give each field the kabupaten/kota it lies in. From the fields you then choose the insured units of the series: the kabupaten/kota with enough rice to insure. Chapter 6 uses the same fields to weight rainfall by where the rice is.

NoteLearning objectives

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

  • reproject a layer whose coordinate system has no EPSG code, and measure what a map projection does to areas;
  • stream a large file into PostGIS in batches with COPY, keeping memory small;
  • assign polygons to administrative units with ST_PointOnSurface and a spatial join, and show why not ST_Centroid;
  • speed up a point-in-polygon join over large polygons with ST_Subdivide;
  • define units of analysis with GROUP BY ... HAVING, with the rule kept as one reproducible query;
  • measure with EXPLAIN (ANALYZE) what a spatial database index saves on a large table.

Before running this chapter:

  • complete Chapter 2 and Chapter 3, whose ref.kabupaten gives each field its unit;
  • be online for the first run, which downloads two files (about 940 MB) into data_dir; later runs find them there;
  • have about 2 GB of free memory and about 3 GB of free space for the database (section 5 prints the sizes);
  • allow about 13 minutes for the whole chapter, most of it in sections 4 and 5, which print their progress. 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 Chapter 3, checks that ref.kabupaten is there, and sets the one parameter of this chapter, MIN_HA, the paddy area a kabupaten/kota needs to become an insured unit (section 6).

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

import datetime as dt
import hashlib
import json
import time
from pathlib import Path

import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
import psycopg
import pyarrow.parquet as pq
import pyproj
import requests
import shapely
import yaml
from psycopg import sql
from sqlalchemy import URL, create_engine

T0 = time.perf_counter()
MIN_HA = 1000                                      # paddy area (ha) of an insured unit, section 6

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("from Chapter 3: ref.kabupaten", conn.execute("SELECT count(*) FROM ref.kabupaten").fetchone()[0], "rows")
connected | POSTGIS="3.7.0 3.7.0" [EXTENSION] PGSQL="180" GEOS="3.15.1-C ...
from Chapter 3: ref.kabupaten 119 rows

2. The rice fields of Java

The fields come from the Ministry of Agriculture (Kementerian Pertanian): two layers for Java dated 2015, one of irrigated and one of rainfed rice fields, with an irrigation class for each field (ledger L39). The irrigated classes are irigasi teknis, semi teknis and sederhana (technical, semi-technical and simple irrigation); rainfed fields (tadah hujan) have no irrigation, so their water comes from rain. The irrigation class is why the series uses this layer: the newer national map of paddy land, lahan baku sawah 2024, matches the official 2024 area of Java but carries no attributes there (ledger L38).

The series ships the two layers as GeoParquet files with the columns it uses, unchanged in geometry and projection (ledger L154). No licence or terms of use come with the data (ledger L154). The next cell downloads the files if they are not in data_dir yet, printing progress, and checks them against the checksum list in the repository. A download is written to a .part file first, so that a cut download is never taken for a whole file.

PADDY = DATA / "paddy" / "moa2015"
PADDY.mkdir(parents=True, exist_ok=True)
FILES = {regime: PADDY / f"moa-ricefield-java-2015-{regime}.parquet" for regime in ["irrigated", "rainfed"]}
# each line of the checksum file reads "sha256  filename"
expected = {name: sha for sha, name in
            (line.split() for line in (ROOT / CONFIG["paddy"]["checksums"]).read_text().splitlines())}

t = time.perf_counter()
for name, sha in sorted(expected.items()):
    path = PADDY / name
    if not path.exists():
        part = path.with_suffix(".part")
        with requests.get(CONFIG["paddy"]["url"].format(file=name), stream=True, timeout=120) as r:
            r.raise_for_status()
            done = 0
            with open(part, "wb") as f:
                for chunk in r.iter_content(1 << 20):
                    f.write(chunk)
                    done += len(chunk)
                    if done % (100 << 20) < (1 << 20):
                        print(f"  {name}: {done / 1e6:.0f} MB", flush=True)
        part.replace(path)
    digest = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 24), b""):
            digest.update(chunk)
    if digest.hexdigest() != sha:
        raise ValueError(f"{name}: checksum does not match; delete the file and run the cell again")
    print(f"{name}: {path.stat().st_size / 1e6:.1f} MB, checksum matches")
print(f"({time.perf_counter() - t:.0f} s)")
moa-ricefield-java-2015-irrigated.parquet: 501.4 MB, checksum matches
moa-ricefield-java-2015-rainfed.parquet: 440.4 MB, checksum matches
(3 s)

3. A projection without an EPSG code

EPSG is a public registry that numbers coordinate systems: EPSG:4326, used for every table so far, is longitude and latitude on the WGS 84 spheroid. A map projection turns the curved surface into a flat plane with x and y in metres, and every projection distorts something. This layer uses a Mercator projection with its own settings (ledger L154), which has no EPSG number. The file therefore stores the full description of its coordinate system in its metadata, as PROJJSON (a JSON form of the description); the cell prints it as WKT, Well-Known Text, another standard text form.

The cell reads only what it needs: the number of rows from the files’ metadata, and the irrigated fields of one kabupaten, Indramayu on the north coast of Jawa Barat, with a filter on the ministry’s code (KODE_BPS).

for regime, path in FILES.items():
    print(f"{regime}: {pq.read_metadata(path).num_rows:,} fields")
indramayu = gpd.read_parquet(FILES["irrigated"], filters=[("KODE_BPS", "==", 3212)])
crs = indramayu.crs
print("EPSG code:", crs.to_epsg(), "| name:", crs.name, "| units:", crs.axis_info[0].unit_name)
print("\n".join(crs.to_wkt(pretty=True).splitlines()[:22]), "\n...")
indramayu.drop(columns="geometry").head()
irrigated: 568,025 fields
rainfed: 390,181 fields
EPSG code: None | name: Custom | units: metre
PROJCRS["Custom",
    BASEGEOGCRS["WGS 84",
        DATUM["World Geodetic System 1984",
            ELLIPSOID["WGS 84",6378137,298.257223563,
                LENGTHUNIT["metre",1]],
            ID["EPSG",6326]],
        PRIMEM["Greenwich",0,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8901]]],
    CONVERSION["unnamed",
        METHOD["Mercator (variant B)",
            ID["EPSG",9805]],
        PARAMETER["Latitude of 1st standard parallel",0,
            ANGLEUNIT["Degree",0.0174532925199433],
            ID["EPSG",8823]],
        PARAMETER["Longitude of natural origin",90,
            ANGLEUNIT["Degree",0.0174532925199433],
            ID["EPSG",8802]],
        PARAMETER["False easting",0,
            LENGTHUNIT["metre",1],
            ID["EPSG",8806]],
        PARAMETER["False northing",1500000, 
...
OBJECTID KODE_BPS IRIGASI_09 INTENS_09 PRODUK_09 HECTARES
0 1047 3212.0 Irigasi Teknis 2x padi/th > 4,5 Ton/Ha 0.407200
1 311214 3212.0 Irigasi Teknis 2x padi/th > 4,5 Ton/Ha 70.827305
2 317830 3212.0 Irigasi Teknis 2x padi/th > 4,5 Ton/Ha 62.711235
3 317848 3212.0 Irigasi Teknis 2x padi/th > 4,5 Ton/Ha 243.260101
4 318186 3212.0 Irigasi Teknis 2x padi/th > 4,5 Ton/Ha 100.196248

Look before moving on. No EPSG code, a projection named “Custom” based on Mercator, units in metres. The columns: KODE_BPS, a kabupaten code written by the ministry, stored as a decimal number (3212.0); IRIGASI_09, the irrigation class; INTENS_09 and PRODUK_09, cropping intensity and yield classes, which the series does not use; and HECTARES, an area the ministry computed.

How does this projection treat areas? The next cell measures the total area of Indramayu’s irrigated fields two ways: on the flat Mercator plane of the file, and in an equal-area projection, EPSG:6933, whose flat areas equal areas on the spheroid (EPSG:6933); and it shows the file’s HECTARES next to them.

mercator_ha = indramayu.area.sum() / 1e4
equal_area_ha = indramayu.to_crs(6933).area.sum() / 1e4
print(f"Indramayu, irrigated fields: {len(indramayu):,} | Mercator plane {mercator_ha:,.0f} ha | "
      f"equal-area {equal_area_ha:,.0f} ha | file HECTARES {indramayu.HECTARES.sum():,.0f} ha")
print(f"the Mercator plane overstates the area by {mercator_ha / equal_area_ha - 1:.1%}")
Indramayu, irrigated fields: 15,814 | Mercator plane 113,176 ha | equal-area 111,759 ha | file HECTARES 113,176 ha
the Mercator plane overstates the area by 1.3%

On the Mercator plane the fields of Indramayu come out 1.3% too large. The file’s HECTARES field equals the Mercator area: the ministry measured its fields on this projection, for every field in both files (ledger L156). Section 5 shows that the stretch is larger for Java as a whole than for Indramayu, because it grows with the distance from the equator. Areas in this series therefore never come from the file’s Mercator plane: the series measures every field on the spheroid in the database (section 5).

4. Into the database, in batches

The fields are moved to EPSG:4326 before they reach the database, the coordinate system of ref.kabupaten, so that the two can be joined. PostGIS can transform a geometry whose projection is given as text (ST_Transform(geom, from_proj, 4326)), but it then reads the projection’s description again for every row: for this layer, minutes per 20,000 fields (ledger L158). It could instead learn the projection once, as a new row in spatial_ref_sys, PostGIS’s table of known coordinate systems, whose row number is the SRID. The simpler way, used here, is to let geopandas transform the fields in Python with the description from the file; it agrees with PostGIS to the last bits of a coordinate (ledger L158).

Reading a whole file and transforming it at once takes 6 GB of memory or more (ledger L158). So the cell streams each file instead: pyarrow reads it 50,000 rows at a time (iter_batches), and each batch is transformed and written to the database before the next is read. Writing uses COPY, PostgreSQL’s bulk loader (Chapter 3), with each geometry sent as EWKB in hexadecimal, a compact binary form that carries the SRID.

Every field gets a number, fid, in the order of the files (irrigated first), which stays its key from here on: the ministry’s own OBJECTID is shared by hundreds of thousands of different fields and cannot be a key (ledger L156). Single polygons are made multipolygons (MultiPolygon([p])), so that the column has one geometry type. Column names are lower case, as PostgreSQL folds unquoted names to lower case. The raw table is replaced if the cell runs again before section 5 has built ref.paddy_moa2015.

RAW_DDL = """
CREATE TABLE raw.paddy_moa2015 (
    fid         bigint PRIMARY KEY,                -- row number over both files, irrigated first
    regime      text NOT NULL,                     -- irrigated or rainfed: which file
    objectid    bigint,
    kode_bps    double precision,
    irigasi_09  text,
    intens_09   text,
    produk_09   text,
    hectares    double precision,                  -- the ministry's area (on its Mercator plane, ledger L156)
    geometry    geometry(MultiPolygon, 4326) NOT NULL
)"""
COPY_RAW = ("COPY raw.paddy_moa2015 (fid, regime, objectid, kode_bps, irigasi_09, intens_09, produk_09, "
            "hectares, geometry) FROM STDIN")
BATCH = 50_000


def file_crs(path: Path) -> pyproj.CRS:
    """The coordinate system stored in a GeoParquet file's metadata (PROJJSON)."""
    geo = json.loads(pq.ParquetFile(path).schema_arrow.metadata[b"geo"])
    return pyproj.CRS.from_json_dict(geo["columns"]["geometry"]["crs"])


with connect() as conn:
    have_ref = conn.execute("SELECT to_regclass('ref.paddy_moa2015')").fetchone()[0]
if have_ref:
    print("ref.paddy_moa2015 already exists: raw load skipped")
else:
    t, fid = time.perf_counter(), 0
    with connect() as conn:
        conn.execute("DROP TABLE IF EXISTS raw.paddy_moa2015")
        conn.execute(RAW_DDL)
        with conn.cursor().copy(COPY_RAW) as cp:
            for regime, path in FILES.items():
                crs = file_crs(path)
                for batch in pq.ParquetFile(path).iter_batches(batch_size=BATCH):
                    df = batch.to_pandas()
                    geom = gpd.GeoSeries(shapely.from_wkb(df.pop("geometry")), crs=crs).to_crs(4326).values
                    single = shapely.get_type_id(geom) == 3                # 3 = Polygon
                    geom[single] = [shapely.MultiPolygon([g]) for g in geom[single]]
                    ewkb = shapely.to_wkb(shapely.set_srid(geom, 4326), hex=True, include_srid=True)
                    for row, g in zip(df.itertuples(index=False), ewkb):
                        cp.write_row((fid, regime, row.OBJECTID, row.KODE_BPS, row.IRIGASI_09, row.INTENS_09,
                                      row.PRODUK_09, row.HECTARES, g))
                        fid += 1
                    if fid % 200_000 < BATCH:
                        print(f"  {fid:,} fields | {time.perf_counter() - t:.0f} s", flush=True)
        conn.execute("COMMENT ON TABLE raw.paddy_moa2015 IS " + sql.quote(
            f"MoA rice fields of Java 2015 from {', '.join(p.name for p in FILES.values())} (ledger L154), "
            f"reprojected to EPSG:4326 in geopandas; loaded {dt.date.today()} by Chapter 5"))
    print(f"raw.paddy_moa2015: {fid:,} fields in {time.perf_counter() - t:.0f} s")
  200,000 fields | 66 s
  400,000 fields | 107 s
  618,025 fields | 150 s
  818,025 fields | 242 s
raw.paddy_moa2015: 958,206 fields in 275 s

Look before moving on. The raw table should hold every field of both files, 568,025 + 390,181 = 958,206 (the counts printed in section 3), all in SRID 4326 and within Java’s longitudes and latitudes. An SRID of 0, or coordinates in the hundreds of thousands, would mean the transformation did not happen.

with connect() as conn:
    print(dict(zip(["fields", "srids", "west", "east", "south", "north"], conn.execute("""
        SELECT count(*), array_agg(DISTINCT ST_SRID(geometry)),
               round(min(ST_XMin(geometry))::numeric, 2), round(max(ST_XMax(geometry))::numeric, 2),
               round(min(ST_YMin(geometry))::numeric, 2), round(max(ST_YMax(geometry))::numeric, 2)
        FROM raw.paddy_moa2015""").fetchone())))
{'fields': 958206, 'srids': [4326], 'west': Decimal('105.48'), 'east': Decimal('114.43'), 'south': Decimal('-8.62'), 'north': Decimal('-5.88')}

5. Repair, assign and measure in SQL

Three things turn the raw copy into ref.paddy_moa2015, all in one statement:

  • repair: as in Chapter 3, ST_MakeValid repairs polygons whose edges cross, ST_CollectionExtract(..., 3) keeps the polygon parts and ST_Multi keeps the type; the raw table stays as loaded;
  • assign: each field belongs to the kabupaten/kota that contains a point inside it, from ST_PointOnSurface, a point guaranteed to lie on the polygon. ST_Centroid, the centre of mass, can fall outside a curved or ring-shaped field (ST_Centroid); the check after this section counts how often. A field that crosses a boundary is not split: it counts whole for the unit of its inside point. A field whose point lies in no kabupaten/kota is left out;
  • measure: ST_Area(geometry::geography) measures each field on the spheroid, in square metres, divided by 10,000 for hectares.

First the speed-up. A point-in-polygon test costs time in proportion to the polygon’s number of vertices, and the kabupaten/kota of Chapter 3 have 2.9 million vertices in all (ledger L146). ST_Subdivide cuts each into pieces of at most 256 vertices (ST_Subdivide). With a GiST index on the pieces, each point is tested only against the few small pieces whose bounding boxes contain it. Building the table against the whole kabupaten/kota took about 25 minutes on the author’s computer, against the pieces about 6 (ledger L157). The pieces go into a table of their own, UNLOGGED because it is thrown away after the next step (PostgreSQL then skips the write-ahead log, its crash journal).

with connect() as conn:
    t = time.perf_counter()
    conn.execute("DROP TABLE IF EXISTS raw.kabupaten_piece")
    conn.execute("CREATE UNLOGGED TABLE raw.kabupaten_piece AS "
                 "SELECT code, ST_Subdivide(geometry, 256) AS geometry FROM ref.kabupaten")
    conn.execute("CREATE INDEX ON raw.kabupaten_piece USING gist (geometry)")
    conn.execute("ANALYZE raw.kabupaten_piece")
    n = conn.execute("SELECT count(*) FROM raw.kabupaten_piece").fetchone()[0]
print(f"119 kabupaten/kota cut into {n:,} pieces in {time.perf_counter() - t:.0f} s")
119 kabupaten/kota cut into 25,013 pieces in 16 s

Now the table itself: defined first, so that its key is id, the fid of section 4, and a field that matched two pieces would be refused by the primary key instead of counted twice. This is the long step: about five minutes, with no output until it ends.

PADDY_DDL = """
CREATE TABLE ref.paddy_moa2015 (
    id              bigint PRIMARY KEY,            -- fid of raw.paddy_moa2015
    regime          text NOT NULL,
    objectid        bigint,
    irigasi_09      text,
    intens_09       text,
    produk_09       text,
    hectares        double precision,
    kode_bps        double precision,
    kabupaten_code  char(4) NOT NULL,
    area_ha         double precision NOT NULL,
    geometry        geometry(MultiPolygon, 4326) NOT NULL
)"""
PADDY_FILL = """
INSERT INTO ref.paddy_moa2015
SELECT s.fid, s.regime, s.objectid, s.irigasi_09, s.intens_09, s.produk_09, s.hectares, s.kode_bps,
       k.code, ST_Area(s.geometry::geography) / 10000, s.geometry
FROM (SELECT fid, regime, objectid, irigasi_09, intens_09, produk_09, hectares, kode_bps,
             CASE WHEN ST_IsValid(geometry) THEN geometry
                  ELSE ST_Multi(ST_CollectionExtract(ST_MakeValid(geometry), 3)) END AS geometry
      FROM raw.paddy_moa2015) s
JOIN raw.kabupaten_piece k ON ST_Intersects(k.geometry, ST_PointOnSurface(s.geometry))
WHERE NOT ST_IsEmpty(s.geometry)"""

with connect() as conn:
    if conn.execute("SELECT to_regclass('ref.paddy_moa2015')").fetchone()[0]:
        print("ref.paddy_moa2015 already exists: left as it is")
    else:
        t = time.perf_counter()
        conn.execute(PADDY_DDL)
        n = conn.execute(PADDY_FILL).rowcount
        print(f"ref.paddy_moa2015: {n:,} fields in {time.perf_counter() - t:.0f} s")
ref.paddy_moa2015: 958,169 fields in 291 s

Then the finishing touches, each timed: the foreign key to ref.kabupaten, a GiST index for spatial queries, an index on kabupaten_code for queries about one kabupaten/kota, a comment, fresh statistics, and the pieces dropped. The cell ends with the sizes of the two tables.

with connect() as conn:
    steps = [
        ("foreign key", "ALTER TABLE ref.paddy_moa2015 ADD FOREIGN KEY (kabupaten_code) REFERENCES ref.kabupaten (code)"),
        ("GiST index", "CREATE INDEX IF NOT EXISTS paddy_moa2015_geometry_gist ON ref.paddy_moa2015 USING gist (geometry)"),
        ("kabupaten index", "CREATE INDEX IF NOT EXISTS paddy_moa2015_kabupaten ON ref.paddy_moa2015 (kabupaten_code)"),
        ("statistics", "ANALYZE ref.paddy_moa2015"),
        ("drop pieces", "DROP TABLE IF EXISTS raw.kabupaten_piece"),
    ]
    has_fk = conn.execute("""SELECT count(*) FROM pg_constraint
                             WHERE conrelid = 'ref.paddy_moa2015'::regclass AND contype = 'f'""").fetchone()[0]
    for name, statement in steps[1 if has_fk else 0:]:
        t = time.perf_counter()
        conn.execute(statement)
        print(f"{name}: {time.perf_counter() - t:.0f} s")
    conn.execute("COMMENT ON TABLE ref.paddy_moa2015 IS " + sql.quote(
        f"MoA rice fields of Java 2015 (ledger L154): repaired, kabupaten/kota by inside point, area_ha on the "
        f"spheroid; built {dt.date.today()} by Chapter 5"))
    print(dict(zip(["raw.paddy_moa2015", "ref.paddy_moa2015"], conn.execute(
        "SELECT pg_size_pretty(pg_total_relation_size('raw.paddy_moa2015')), "
        "pg_size_pretty(pg_total_relation_size('ref.paddy_moa2015'))").fetchone())))
foreign key: 53 s
GiST index: 5 s
kabupaten index: 4 s
statistics: 1 s
drop pieces: 0 s
{'raw.paddy_moa2015': '1555 MB', 'ref.paddy_moa2015': '1464 MB'}

Look before moving on. Four checks. First, what was left out: the fields of the raw table that are not in ref.paddy_moa2015 should be few, and none of them should be an empty geometry; they are fields whose inside point lies in no kabupaten/kota, offshore or outside Java. Second, why ST_PointOnSurface: how many fields have their centroid outside themselves, where a centroid would have put them in the wrong unit or in none.

with connect() as conn:
    lost = conn.execute("""SELECT count(*), count(*) FILTER (WHERE ST_IsEmpty(geometry)), round(sum(hectares))
                           FROM raw.paddy_moa2015 r
                           WHERE NOT EXISTS (SELECT 1 FROM ref.paddy_moa2015 p WHERE p.id = r.fid)""").fetchone()
    outside = conn.execute("""SELECT count(*), round(sum(area_ha)) FROM ref.paddy_moa2015
                              WHERE NOT ST_Intersects(geometry, ST_Centroid(geometry))""").fetchone()
print(f"left out: {lost[0]} fields ({lost[1]} empty, {lost[2]} ha by the file's own measure)")
print(f"fields whose centroid lies outside the field: {outside[0]:,} ({outside[1]:,.0f} ha)")
left out: 37 fields (0 empty, 135.0 ha by the file's own measure)
fields whose centroid lies outside the field: 67,201 (278,401 ha)

Third, the totals: fields and hectares per irrigation class from the spheroid areas, next to the file’s HECTARES (the Mercator area). GROUP BY ROLLUP (regime, irigasi_09) adds subtotal rows, one per regime and one grand total; GROUPING(column) is 1 on the rows where that column has been rolled up, which the query uses to label them all.

TOTALS = """
SELECT CASE WHEN GROUPING(regime) = 1 THEN 'all' ELSE regime END AS regime,
       CASE WHEN GROUPING(irigasi_09) = 1 THEN 'all' ELSE irigasi_09 END AS irigasi_09,
       count(*) AS fields, round(sum(area_ha)) AS area_ha, round(sum(hectares)) AS file_hectares,
       round((sum(hectares) / sum(area_ha) - 1)::numeric * 100, 2) AS mercator_excess_pct
FROM ref.paddy_moa2015
GROUP BY ROLLUP (regime, irigasi_09)
ORDER BY GROUPING(regime), regime, GROUPING(irigasi_09), irigasi_09"""
with connect() as conn:
    totals = pd.DataFrame(conn.execute(TOTALS).fetchall(),
                          columns=["regime", "irigasi_09", "fields", "area_ha", "file_hectares", "mercator_excess_pct"])
totals
regime irigasi_09 fields area_ha file_hectares mercator_excess_pct
0 irrigated Irigasi Sederhana 76207 169185.0 171891.0 1.60
1 irrigated Irigasi Semi Teknis 239046 1026726.0 1044317.0 1.71
2 irrigated Irigasi Teknis 252741 1449425.0 1471087.0 1.49
3 irrigated all 567994 2645336.0 2687294.0 1.59
4 rainfed Tadah Hujan 390175 746236.0 758198.0 1.60
5 rainfed all 390175 746236.0 758198.0 1.60
6 all all 958169 3391572.0 3445492.0 1.59

The irrigation class follows the regime: the rainfed file holds only tadah hujan. For Java as a whole the file’s Mercator areas exceed the spheroid areas by more than they did for Indramayu: much of Java’s paddy lies farther from the equator, and the Mercator stretch grows with the distance (section 3).

Fourth, the assignment against the ministry’s own codes. Each field carries KODE_BPS; the query counts how often it equals the kabupaten/kota found by location (kode_bps::int::text turns 3212.0 into ‘3212’), and lists the largest groups where the two differ.

with connect() as conn:
    agree = conn.execute("""SELECT count(*), count(*) FILTER (WHERE kode_bps::int::text = kabupaten_code),
                                   round(sum(area_ha) FILTER (WHERE kode_bps::int::text <> kabupaten_code))
                            FROM ref.paddy_moa2015""").fetchone()
    differ = pd.DataFrame(conn.execute("""
        SELECT p.kode_bps::int AS ministry_code, c.name AS ministry_name, p.kabupaten_code AS by_location,
               k.name AS location_name, count(*) AS fields, round(sum(p.area_ha)) AS ha
        FROM ref.paddy_moa2015 p
        JOIN ref.kabupaten k ON k.code = p.kabupaten_code
        LEFT JOIN ref.kabupaten c ON c.code = p.kode_bps::int::text
        WHERE p.kode_bps::int::text <> p.kabupaten_code
        GROUP BY 1, 2, 3, 4 ORDER BY ha DESC LIMIT 5""").fetchall(),
        columns=["ministry_code", "ministry_name", "by_location", "location_name", "fields", "ha"])
print(f"{agree[1]:,} of {agree[0]:,} fields ({agree[1] / agree[0]:.1%}) carry the code of their location; "
      f"{agree[2]:,.0f} ha do not")
differ
942,673 of 958,169 fields (98.4%) carry the code of their location; 32,060 ha do not
ministry_code ministry_name by_location location_name fields ha
0 3207 Ciamis 3218 Pangandaran 4951 17243.0
1 0 NaN 3312 Wonogiri 340 1637.0
2 3278 Kota Tasikmalaya 3206 Tasikmalaya 828 1312.0
3 3311 Sukoharjo 3313 Karanganyar 468 712.0
4 3604 Serang 3673 Kota Serang 158 693.0

Nearly all fields carry the code of the unit they lie in. Most of the area that does not is in one group: fields the ministry coded as Ciamis that lie in Pangandaran, a kabupaten with a code of its own in the boundary file. Code 0 means the ministry wrote no code at all (ledger L158). The series assigns by location, so these codes do not affect the units.

Finally a spot check against section 3: Indramayu’s irrigated fields, by location, should hold close to the 111,759 ha measured there in an equal-area projection (the sets differ slightly, since section 3 selected by the ministry’s code).

with connect() as conn:
    print(dict(zip(["fields", "area_ha"], conn.execute("""SELECT count(*), round(sum(area_ha)) FROM ref.paddy_moa2015
                                                         WHERE kabupaten_code = '3212' AND regime = 'irrigated'""").fetchone())))
{'fields': 15797, 'area_ha': 111734.0}

6. Insured units

An insurance contract needs units: the areas for which the index is computed and a payout is made. This series insures kabupaten/kota, the finest level at which the damage reports of Chapter 3 exist (ledger L1), and only those with at least MIN_HA = 1,000 ha of rice fields. Below that are cities with little paddy left: all 20 units under 1,000 ha are kota or Kepulauan Seribu, together holding 0.22% of Java’s paddy (ledger L40), and a contract for them would insure almost nothing. Smaller units, kecamatan, were considered: a kecamatan’s rainfall correlates with its kabupaten’s at a median of 0.99 (ledger L42), and against the reported drought damage a kecamatan index ranks events no better (ledger L43).

GROUP BY sums the fields per kabupaten/kota, FILTER splits the sum by regime, coalesce turns “no rainfed fields” into 0 ha (a true zero here, not a missing value), and HAVING keeps the units above the threshold. round works on the type numeric, hence the casts. The threshold is passed as a parameter (%(min_ha)s), which psycopg can do here because CREATE TABLE ... AS contains a query; it cannot do it inside a table definition. The result is a small table, idx.insured_unit, that every later chapter joins to. To try another threshold, drop the table first (see Troubleshooting) or run the query without CREATE TABLE ... AS.

INSURED_UNIT = """
CREATE TABLE idx.insured_unit AS
SELECT k.code, k.name,
       round(sum(p.area_ha)::numeric, 1) AS paddy_ha,
       round(coalesce(sum(p.area_ha) FILTER (WHERE p.regime = 'irrigated'), 0)::numeric, 1) AS irrigated_ha,
       round(coalesce(sum(p.area_ha) FILTER (WHERE p.regime = 'rainfed'), 0)::numeric, 1) AS rainfed_ha
FROM ref.kabupaten k
JOIN ref.paddy_moa2015 p ON p.kabupaten_code = k.code
GROUP BY k.code, k.name
HAVING sum(p.area_ha) >= %(min_ha)s"""

with connect() as conn:
    if conn.execute("SELECT to_regclass('idx.insured_unit')").fetchone()[0]:
        print("idx.insured_unit already exists: left as it is")
    else:
        conn.execute(INSURED_UNIT, {"min_ha": MIN_HA})
        conn.execute("ALTER TABLE idx.insured_unit ADD PRIMARY KEY (code)")
        conn.execute("ALTER TABLE idx.insured_unit ADD FOREIGN KEY (code) REFERENCES ref.kabupaten (code)")
        conn.execute("COMMENT ON TABLE idx.insured_unit IS " + sql.quote(
            f"Insured units: kabupaten/kota with at least {MIN_HA:,} ha of MoA 2015 paddy (ref.paddy_moa2015); "
            f"built {dt.date.today()} by Chapter 5"))
    units = pd.DataFrame(conn.execute("""
        SELECT count(*), round(sum(paddy_ha)), round(min(paddy_ha)),
               round(percentile_cont(0.5) WITHIN GROUP (ORDER BY paddy_ha)), round(max(paddy_ha)),
               (SELECT round(sum(area_ha)) FROM ref.paddy_moa2015)
        FROM idx.insured_unit""").fetchall(),
        columns=["units", "paddy_ha", "smallest", "median", "largest", "java_paddy_ha"])
units
units paddy_ha smallest median largest java_paddy_ha
0 99 3384143 1186 31220.0 117256 3391572.0

percentile_cont(0.5) WITHIN GROUP (ORDER BY paddy_ha) is the median: an ordered-set aggregate, which needs the values in order. Look before moving on. The units hold almost all of Java’s paddy: compare paddy_ha with java_paddy_ha. The next query lists the kabupaten/kota left out, with their paddy area: they should be cities (kota) and the islands of Kepulauan Seribu (whose type was cut short in the source, Chapter 3), each with little or no rice.

with connect() as conn:
    left_out = pd.DataFrame(conn.execute("""
        SELECT k.code, k.name, k.type, count(p.id) AS fields, round(coalesce(sum(p.area_ha), 0)) AS paddy_ha
        FROM ref.kabupaten k
        LEFT JOIN ref.paddy_moa2015 p ON p.kabupaten_code = k.code
        WHERE k.code NOT IN (SELECT code FROM idx.insured_unit)
        GROUP BY k.code, k.name, k.type
        ORDER BY paddy_ha DESC""").fetchall(), columns=["code", "name", "type", "fields", "paddy_ha"])
print(len(left_out), "left out |", left_out.type.value_counts().to_dict(),
      f"| largest left out {left_out.paddy_ha.max():,.0f} ha, smallest unit {units.smallest[0]:,.0f} ha")
left_out.head(8)
20 left out | {'Kota': 14, 'Kota Administrasi': 5, 'Kabupaten Administr*': 1} | largest left out 908 ha, smallest unit 1,186 ha
code name type fields paddy_ha
0 3577 Kota Madiun Kota 230 908.0
1 3572 Kota Blitar Kota 98 789.0
2 3275 Kota Bekasi Kota 235 743.0
3 3376 Kota Tegal Kota 122 742.0
4 3373 Kota Salatiga Kota 344 670.0
5 3271 Kota Bogor Kota 271 628.0
6 3175 Kota Administrasi Jakarta Utara Kota Administrasi 35 484.0
7 3576 Kota Mojokerto Kota 61 375.0

The largest kabupaten/kota left out and the smallest unit kept are some way apart, so a threshold anywhere between them gives the same units. A map of the units, shaded by the share of their paddy that is rainfed, shows where rainfed rice makes up much of the paddy; the cell also lists the five units with the highest share. The shapes are simplified for drawing, as in Chapter 3.

MAP = """
SELECT k.code, k.name, u.paddy_ha, u.rainfed_ha / u.paddy_ha AS rainfed_share,
       ST_CoverageSimplify(k.geometry, 0.005) OVER () AS geometry
FROM ref.kabupaten k LEFT JOIN idx.insured_unit u ON u.code = k.code"""
m = gpd.read_postgis(MAP, ENGINE, geom_col="geometry")
m["rainfed_share"] = m.rainfed_share.astype(float)
fig, ax = plt.subplots(figsize=(10, 3.6))
m[m.paddy_ha.isna()].plot(ax=ax, color="0.85", edgecolor="white", linewidth=0.3)
m[m.paddy_ha.notna()].plot(ax=ax, column="rainfed_share", cmap="YlOrBr", vmin=0, vmax=1, edgecolor="white",
                           linewidth=0.3, legend=True, legend_kwds={"label": "rainfed share of paddy", "shrink": 0.7})
ax.set_title(f"{m.paddy_ha.notna().sum()} insured units (colour) and {m.paddy_ha.isna().sum()} others (grey)")
ax.set_axis_off()
plt.show()
m.dropna(subset=["paddy_ha"]).nlargest(5, "rainfed_share")[["code", "name", "paddy_ha", "rainfed_share"]].round(2)

Map of Java's insured units shaded by the rainfed share of their paddy, with the kabupaten/kota that are not insured in grey.

code name paddy_ha rainfed_share
67 3403 Gunungkidul 27408.8 0.96
97 3528 Pamekasan 25495.8 0.90
39 3307 Wonosobo 18823.7 0.90
98 3529 Sumenep 20361.3 0.89
7 3202 Sukabumi 54508.0 0.74

7. A closer look at the fields

The units are built from fields, so it is worth seeing what a field polygon is. The map shows the fields in a 4 by 4 km square in the west of Indramayu where irrigated and rainfed fields lie side by side. The query first compares bounding boxes with &&, which uses the GiST index, and then keeps the fields that really intersect the square with ST_Intersects. Change BOX to look elsewhere.

BOX = dict(x0=107.959, y0=-6.592, x1=107.995, y1=-6.556)        # about 4 by 4 km
fields = gpd.read_postgis("""
    SELECT p.irigasi_09, p.area_ha, p.kabupaten_code, p.geometry
    FROM ref.paddy_moa2015 p,
         LATERAL (SELECT ST_MakeEnvelope(%(x0)s, %(y0)s, %(x1)s, %(y1)s, 4326) AS box) b
    WHERE p.geometry && b.box AND ST_Intersects(p.geometry, b.box)""", ENGINE, geom_col="geometry", params=BOX)
with connect() as conn:
    java_median = conn.execute("SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY area_ha) "
                               "FROM ref.paddy_moa2015").fetchone()[0]
fig, ax = plt.subplots(figsize=(6, 6))
fields.plot(ax=ax, column="irigasi_09", categorical=True, legend=True, edgecolor="0.3", linewidth=0.2,
            legend_kwds={"loc": "lower left", "fontsize": 7})
ax.set_xlim(BOX["x0"], BOX["x1"]); ax.set_ylim(BOX["y0"], BOX["y1"])
ax.set_title(f"{len(fields)} fields intersecting a 4 x 4 km square")
ax.set_axis_off()
plt.show()
print("units:", fields.kabupaten_code.unique().tolist(), "| classes:", fields.irigasi_09.value_counts().to_dict())
print(f"field size here: median {fields.area_ha.median():.2f} ha, largest {fields.area_ha.max():.1f} ha | "
      f"Java-wide median {java_median:.2f} ha")

Close-up map of rice-field polygons in a 4 by 4 km square in Kabupaten Indramayu, coloured by irrigation class, with irrigated and rainfed fields side by side.

units: ['3212'] | classes: {'Irigasi Teknis': 309, 'Tadah Hujan': 129}
field size here: median 0.55 ha, largest 122.0 ha | Java-wide median 0.42 ha

Look before moving on. The square lies wholly in Indramayu (3212) and holds both irrigated and rainfed fields. The polygons vary a great deal in size, from fractions of a hectare to tens of hectares, with unmapped land between them. The insured unit adds all of them up, and Chapter 6 places each on the rainfall grid by its inside point.

8. What the database index buys

First a word on the name, because this series uses “index” in two senses. The drought index of Chapter 8 ranks how dry a season was, and the contract of Chapter 9 pays on it; the schema idx holds the tables of that insurance index. A database index is something else: a lookup structure that PostgreSQL keeps next to a table so that it can find rows without reading all of them, like the index at the back of a book. This section is about the second kind only.

The series uses two kinds of database index. Every primary key comes with a B-tree index, which keeps values such as codes and dates in sorted order, so that a lookup by code or by day goes straight to its rows; section 5 also added one on kabupaten_code. The GiST index on ref.paddy_moa2015 (section 5) is the spatial one: it stores only the bounding box of each field, so that a spatial query can first skip every field whose box lies away from the area it asks about. Chapter 3 showed with EXPLAIN that PostgreSQL chooses such an index; the cell below measures what it saves.

It counts the fields in the square of section 7 with EXPLAIN (ANALYZE, BUFFERS), which runs a query and reports the plan PostgreSQL followed, the time it took and how many 8 kB pages it read. After one run to bring the pages it needs into memory, it does so three times with the index and three times with index and bitmap scans switched off, and keeps the median time of each. The settings (SET LOCAL enable_indexscan = off and enable_bitmapscan = off) last only until the end of the transaction they are set in, and only in this session: the index is not dropped and nothing in the database changes. They tell the planner not to use those scans whenever it has another way, so the cell prints the plan step that actually read the table and checks it.

COUNT_QUERY = """
    SELECT count(*)
    FROM ref.paddy_moa2015 p,
         LATERAL (SELECT ST_MakeEnvelope(%(x0)s, %(y0)s, %(x1)s, %(y1)s, 4326) AS box) b
    WHERE p.geometry && b.box AND ST_Intersects(p.geometry, b.box)"""


def descendants(node):
    yield node
    for child in node.get("Plans", []):
        yield from descendants(child)


def table_step(plan):
    """The plan step that read ref.paddy_moa2015: its type ("Parallel" if split across processes) and index."""
    node = next(n for n in descendants(plan) if n.get("Relation Name") == "paddy_moa2015")
    index = next((n["Index Name"] for n in descendants(node) if "Index Name" in n), None)
    return ("Parallel " if node.get("Parallel Aware") else "") + node["Node Type"], index


def measure(conn, use_index):
    with conn.transaction():                         # SET LOCAL lasts until the end of this block
        conn.execute("SET LOCAL jit = off")          # no compile time in either measurement
        if not use_index:
            conn.execute("SET LOCAL enable_indexscan = off")
            conn.execute("SET LOCAL enable_bitmapscan = off")
        n = conn.execute(COUNT_QUERY, BOX).fetchone()[0]                     # also brings the pages into memory
        runs = [conn.execute("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + COUNT_QUERY, BOX,
                             prepare=False).fetchone()[0][0] for _ in range(3)]
    plan = runs[-1]["Plan"]
    pages = plan["Shared Hit Blocks"] + plan["Shared Read Blocks"]
    return n, table_step(plan), sorted(r["Execution Time"] for r in runs)[1], pages


with connect(autocommit=True) as conn:              # so that each measure() is its own transaction
    n_on, step_on, ms_on, pages_on = measure(conn, use_index=True)
    n_off, step_off, ms_off, pages_off = measure(conn, use_index=False)
    index_size, table_size = conn.execute("""
        SELECT pg_size_pretty(pg_relation_size('ref.paddy_moa2015_geometry_gist')),
               pg_size_pretty(pg_table_size('ref.paddy_moa2015'))""").fetchone()

assert n_on == n_off, f"the two plans counted different fields: {n_on} and {n_off}"
assert step_on[1] == "paddy_moa2015_geometry_gist" and step_off[1] is None, (step_on, step_off)
print(f"fields in the square: {n_on} (the same both ways)")
print(f"with the index:      execution {ms_on:8.2f} ms, {pages_on:7,} pages read  {step_on[0]} using {step_on[1]}")
print(f"index switched off:  execution {ms_off:8.2f} ms, {pages_off:7,} pages read  {step_off[0]}")
print(f"the index made this query {ms_off / ms_on:.0f} times faster; it takes {index_size} "
      f"next to the {table_size} of the table itself")
fields in the square: 438 (the same both ways)
with the index:      execution     1.16 ms,     333 pages read  Index Scan using paddy_moa2015_geometry_gist
index switched off:  execution   656.14 ms, 211,714 pages read  Parallel Seq Scan
the index made this query 566 times faster; it takes 38 MB next to the 1385 MB of the table itself

Look before moving on. Both plans count the same fields. With the index, PostgreSQL reads only the fields whose boxes overlap the square, and runs the exact ST_Intersects test on those alone; without it, it reads every row of the table and tests each one (a “Seq Scan”; “Parallel” means the work was split across several processes, so the gap in effort is larger still than the gap in time). The pages read do not depend on your computer; the times do, and both were measured after a first run had brought the pages into memory (PostgreSQL’s own cache or the operating system’s), so a first query after a restart is slower either way. The gap should stay large wherever you run it: the query asks about a few hundred of nearly a million fields.

A side note on the query: ST_Intersects makes the bounding-box test through the index by itself, so the && in it (and in section 7) only makes that first step visible; leaving it out gives the same index scan and the same count.

An index is not free. It takes the space printed above, on a first run section 5 printed the seconds it took to build, and every later change to the table must update it as well. It pays where a query picks a few rows out of many. The kabupaten_code index shows both sides: the Indramayu check of section 5 uses it, while the sums of section 6, which read every field, do not. For the same reason the daily rainfall rasters of Chapter 4 have no spatial index: each one covers the same Java window, so a bounding box could not rule any of them out, and their primary key on day is the index that matters (Chapter 4).

Checkpoint

The cell below checks, in a new session, what Chapter 6 relies on: every field valid, a MultiPolygon in EPSG:4326 with an area and a kabupaten/kota, each field once (the primary key), a GiST index; every insured unit at or above MIN_HA and no unit above it missing; and in every unit the irrigated and rainfed areas adding up to the total. It depends only on the setup cell.

with connect() as conn:
    first_row = lambda q, p=None: conn.execute(q, p).fetchone()
    n, n_valid, n_null = first_row("""SELECT count(*), count(*) FILTER (WHERE ST_IsValid(geometry)),
                                             count(*) FILTER (WHERE kabupaten_code IS NULL OR area_ha IS NULL)
                                      FROM ref.paddy_moa2015""")
    gtype = first_row("""SELECT type || ' ' || srid FROM geometry_columns
                         WHERE f_table_schema = 'ref' AND f_table_name = 'paddy_moa2015'""")[0]
    keys = first_row("""SELECT (SELECT count(*) FROM pg_constraint WHERE conrelid = 'ref.paddy_moa2015'::regclass
                                AND contype IN ('p', 'f')),
                               (SELECT count(*) FROM pg_indexes WHERE schemaname = 'ref'
                                AND tablename = 'paddy_moa2015' AND indexdef ILIKE '%USING gist%')""")
    n_units, below, off = first_row("""SELECT count(*), count(*) FILTER (WHERE paddy_ha < %(m)s),
                                              count(*) FILTER (WHERE abs(paddy_ha - irrigated_ha - rainfed_ha) > 0.1)
                                       FROM idx.insured_unit""", {"m": MIN_HA})
    missing = first_row("""SELECT count(*) FROM (SELECT kabupaten_code FROM ref.paddy_moa2015 GROUP BY 1
                                                HAVING sum(area_ha) >= %(m)s) a
                           WHERE kabupaten_code NOT IN (SELECT code FROM idx.insured_unit)""", {"m": MIN_HA})[0]
    total = first_row("SELECT sum(paddy_ha) FROM idx.insured_unit")[0]

assert n > 900_000 and n_valid == n and n_null == 0, f"ref.paddy_moa2015: {n} rows, {n_valid} valid, {n_null} incomplete"
assert gtype == "MULTIPOLYGON 4326", f"geometry column: {gtype}"
assert keys == (2, 1), f"primary and foreign key, GiST index: {keys}"
assert n_units > 0 and below == 0 and missing == 0 and off == 0, \
    f"insured units: {n_units}, {below} below {MIN_HA}, {missing} missing, {off} not adding up"
print(f"checkpoint passed: {n:,} fields, {n_units} insured units holding {total:,.0f} ha; "
      f"code cells took {time.perf_counter() - T0:.0f} s since the setup cell")
checkpoint passed: 958,169 fields, 99 insured units holding 3,384,143 ha; code cells took 775 s since the setup cell

Troubleshooting

Symptom Cause Fix
relation "ref.kabupaten" does not exist Chapter 3 has not been run run Chapter 3 first
404 when downloading a file the files are not at the URL in config.yml check paddy.url against the releases page of the repository, https://github.com/osgeoid/postgis-crop-insurance/releases
checksum does not match a download was cut short, or the file was replaced delete that file in data_dir/paddy/moa2015 and run the cell again
MemoryError, or the kernel dies in section 4 less free memory than the batches need close other programs, or set BATCH = 20_000 and run the cell again
section 4 stopped part-way the cell was interrupted run it again: the raw table is rebuilt from the start (as long as ref.paddy_moa2015 does not exist yet)
duplicate key value violates unique constraint "paddy_moa2015_pkey" in section 5 a field matched two pieces of kabupaten/kota this did not happen with the boundaries of Chapter 3 (ledger L157); check that ref.kabupaten has no overlapping shapes
ref.paddy_moa2015 already exists, but you want to rebuild the cells never drop a table that later chapters may use DROP TABLE idx.insured_unit, ref.paddy_moa2015 in a new cell (before Chapter 6 builds on them), then run sections 4 to 6 again
idx.insured_unit already exists after changing MIN_HA the cell does not rebuild an existing table DROP TABLE idx.insured_unit (before Chapter 6 builds on it), then run section 6 again

Summary

You now have:

  • ref.paddy_moa2015: Java’s rice fields with irrigation regime and class, kabupaten/kota (by inside point), area on the spheroid, valid MultiPolygon geometries in EPSG:4326, a GiST index and the key id;
  • idx.insured_unit: the kabupaten/kota with at least 1,000 ha of paddy, with their irrigated and rainfed hectares, the units of every later chapter;
  • raw.paddy_moa2015: the fields as loaded and reprojected, which nothing else uses; drop it to free the space printed in section 5 (DROP TABLE raw.paddy_moa2015);
  • in data_dir: the two paddy files (about 940 MB).

What comes next

Chapter 6 brings rasters and vectors together: it weights the rainfall of Chapter 4 by the paddy area under each cell and computes dekad rainfall for every insured unit.

References