Skip to main content

Chapter 6: Rainfall per insured unit

Chapter 6: Rainfall per insured unit

TipAt a glance
  • You will build: idx.paddy_weight (paddy hectares of each kabupaten/kota and irrigation regime in each rainfall cell) and idx.dekad_rain (paddy-weighted dekad rainfall per kabupaten/kota and regime, 1981 to September 2026)
  • You need: Chapters 3, 4 and 5
  • Time to run: About 3 minutes (the checkpoint prints the time), most of it in section 5
  • Level: Intermediate

An index contract pays on one number per insured unit and period, not on a map. This chapter turns the rainfall rasters of Chapter 4 into that number: the rainfall of each dekad over each kabupaten/kota, weighted by where its rice grows. Rasters and vectors meet here. You first try the direct way, clipping the raster with each unit’s boundary, and see where it falls short; then you build a small weight table that records how many hectares of paddy lie in each rainfall cell, and compute dekad rainfall from 1981 to September 2026 for every unit with one join. A recomputation in numpy checks one dekad of the result.

NoteLearning objectives

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

  • summarise a raster over polygons with ST_Clip and ST_SummaryStats, and say which cells it counts;
  • read a raster’s georeference (ST_UpperLeftX, ST_ScaleX, …) and turn a point into a column and row;
  • build a weight table that links vector features to raster cells, and check it;
  • compute weighted means over many rasters at once with ST_PixelAsPoints and a join;
  • check a database result against an independent computation in numpy.

Before running this chapter:

  • complete Chapter 3 (the boundaries ref.kabupaten), Chapter 4 (the dekad rasters idx.chirps_dekad) and Chapter 5 (the paddy fields ref.paddy_moa2015 and the insured units idx.insured_unit);
  • allow about 3 minutes for the whole chapter. No downloads are needed. A step whose table already exists is skipped on a second run.

1. Setup

The setup cell reads config.yml, defines connect() and ENGINE as in the earlier chapters, and checks that the tables of Chapters 3 to 5 are there. Two settings pick what the chapter looks at closely:

  • UNIT, a kabupaten/kota: Garut, in Jawa Barat, whose paddy is about half irrigated and half rainfed (section 5 prints the hectares), so both regimes can be compared in one unit;
  • DEKAD, the first day of a dekad (the 1st, 11th or 21st of a month) used in single-dekad examples: a dekad in the rainy season of 2019, so the maps and checks have rain to show.

Change either to look elsewhere; the cell checks that UNIT is an insured unit and DEKAD a dekad in idx.chirps_dekad.

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

import datetime as dt
import time
import warnings
from pathlib import Path

import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import psycopg
import yaml
from psycopg import sql
from rasterio.io import MemoryFile
from sqlalchemy import URL, create_engine

# silences a DeprecationWarning raised inside rasterio on every read
warnings.filterwarnings("ignore", message="Setting the shape on a NumPy array", category=DeprecationWarning)

T0 = time.perf_counter()
UNIT = "3205"                 # BPS code of Kabupaten Garut
DEKAD = "2019-01-11"          # first day of the dekad used in single-dekad examples

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"]


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], "...")
    for table in ["ref.kabupaten", "idx.chirps_dekad", "ref.paddy_moa2015", "idx.insured_unit"]:
        if not conn.execute("SELECT to_regclass(%s)", [table]).fetchone()[0]:
            raise RuntimeError(f"{table} is missing: run Chapters 3 to 5 first")
    print("dekads:", conn.execute("SELECT count(*), min(dekad_start), max(dekad_end) FROM idx.chirps_dekad").fetchone())
    found = conn.execute("SELECT name FROM idx.insured_unit WHERE code = %s", [UNIT]).fetchone()
    if found is None:
        raise ValueError(f"UNIT {UNIT} is not an insured unit: pick a code from idx.insured_unit")
    unit_name = found[0]
    if not conn.execute("SELECT 1 FROM idx.chirps_dekad WHERE dekad_start = %s", [DEKAD]).fetchone():
        raise ValueError(f"DEKAD {DEKAD} is not the first day of a dekad in idx.chirps_dekad")
unit = gpd.read_postgis("SELECT code, geometry FROM ref.kabupaten WHERE code = %(u)s", ENGINE,
                        geom_col="geometry", params={"u": UNIT})
print(f"unit looked at: {UNIT} {unit_name} | dekad: {DEKAD}")
connected | POSTGIS="3.7.0 3.7.0" [EXTENSION] PGSQL="180" GEOS="3.15.1-C ...
dekads: (1647, datetime.date(1981, 1, 1), datetime.date(2026, 9, 30))
unit looked at: 3205 Garut | dekad: 2019-01-11

2. Rain falls on cells, rice grows in fields

Each dekad raster is a grid of cells 0.05 degree wide, about 5.5 km in Java (ledger L146), each holding one rainfall total (Chapter 4). A kabupaten/kota is a polygon, and its rice fields cover only part of it. The map shows the unit UNIT with its paddy fields over the cells of the grid. ST_PixelAsPolygons(rast, 1, false) returns every cell of band 1 as a square polygon with its column x and row y; false keeps the nodata cells too (the sea), so the whole grid can be drawn. The query keeps the cells whose square meets the unit’s bounding box (&&).

LATERAL in the FROM list lets a function call use the columns of the tables named before it: here ST_PixelAsPolygons runs on the rast of each row of idx.chirps_dekad that the WHERE keeps.

grid = gpd.read_postgis("""
    SELECT p.x AS col, p.y AS row, p.val AS mm, p.geom
    FROM idx.chirps_dekad d, LATERAL ST_PixelAsPolygons(d.rast, 1, false) p,
         (SELECT geometry FROM ref.kabupaten WHERE code = %(u)s) k
    WHERE d.dekad_start = %(d)s AND p.geom && k.geometry""", ENGINE, geom_col="geom",
                        params={"u": UNIT, "d": DEKAD})
fields = gpd.read_postgis("SELECT regime, geometry FROM ref.paddy_moa2015 WHERE kabupaten_code = %(u)s",
                          ENGINE, geom_col="geometry", params={"u": UNIT})
fig, ax = plt.subplots(figsize=(7, 6))
grid.boundary.plot(ax=ax, color="0.75", linewidth=0.5)
fields.plot(ax=ax, color="tab:green", linewidth=0)
unit.boundary.plot(ax=ax, color="black", linewidth=0.8)
ax.set_title(f"{unit_name}: {len(fields):,} paddy fields over {len(grid)} rainfall cells")
ax.set_axis_off()
plt.show()

Map of Kabupaten Garut with its paddy fields in green drawn over the square cells of the rainfall grid, showing rice concentrated in some cells and absent from others.

Look before moving on. The fields (green) should lie on the grid and inside the unit’s outline; fields off the grid or outside the outline would mean the layers are in different coordinate systems. The fields crowd into some cells and leave others nearly or wholly empty. A plain mean over all cells of the unit gives each cell the same say; for an index of rice it is the cells with rice that should count, in proportion to how much rice they hold.

3. The direct way: ST_Clip and ST_SummaryStats

ST_Clip(rast, geometry) cuts a raster down to a polygon: cells outside it become nodata. ST_SummaryStats then returns the count, sum, mean and other statistics of the cells left. By default ST_Clip keeps a cell only if the polygon covers the cell’s centre; the PostGIS manual says that with touched => true (since PostGIS 3.5) it keeps every cell the polygon touches (ledger L45). touched => true passes the argument by its name, so the arguments before it can keep their defaults. The query runs both rules for every insured unit and the dekad DEKAD, and lists the units with the fewest cells.

CLIP = """
SELECT u.code, u.name, u.paddy_ha,
       c.count AS cells_centre, round(c.mean::numeric, 1) AS mm_centre,
       t.count AS cells_touched, round(t.mean::numeric, 1) AS mm_touched
FROM idx.insured_unit u
JOIN ref.kabupaten k ON k.code = u.code
JOIN idx.chirps_dekad d ON d.dekad_start = %(d)s
CROSS JOIN LATERAL ST_SummaryStats(ST_Clip(d.rast, k.geometry)) c
CROSS JOIN LATERAL ST_SummaryStats(ST_Clip(d.rast, k.geometry, touched => true)) t
ORDER BY cells_centre, u.code"""
with connect() as conn:
    clip = pd.DataFrame(conn.execute(CLIP, {"d": DEKAD}).fetchall(),
                        columns=["code", "name", "paddy_ha", "cells_centre", "mm_centre", "cells_touched", "mm_touched"])
no_cell = clip[clip.cells_centre == 0]
print(f"units with no cell centre inside: {len(no_cell)} {no_cell.name.tolist()}; "
      f"cells per unit (centre rule): median {clip.cells_centre.median():.0f}, largest {clip.cells_centre.max()}")
clip.head(6)
units with no cell centre inside: 1 ['Kota Pasuruan']; cells per unit (centre rule): median 39, largest 133
code name paddy_ha cells_centre mm_centre cells_touched mm_touched
0 3575 Kota Pasuruan 1315.7 0 None 5 166.1
1 3272 Kota Sukabumi 1594.1 2 137.0 6 136.8
2 3375 Kota Pekalongan 1185.5 2 326.3 4 337.8
3 3571 Kota Kediri 1699.8 2 255.0 8 251.6
4 3574 Kota Probolinggo 2616.5 2 163.8 6 163.6
5 3278 Kota Tasikmalaya 5414.4 5 281.6 14 268.0

Look before moving on. Kota Pasuruan, an insured unit with more than 1,000 ha of rice, has no cell whose centre lies inside it, so the centre rule gives it no rainfall at all (mm_centre is empty). touched => true gives it cells, and other small units gain cells too (compare cells_touched with cells_centre). But now a cell that grazes the unit’s edge counts as much as a cell full of rice in its middle, and cells with no rice count too. Both rules answer “how much rain fell on this polygon”, not “how much rain fell on its rice”.

Do not take a function’s description on trust either. Compared with the cells whose square intersects the unit (ST_PixelAsPolygons with ST_Intersects), touched => true in PostGIS 3.7.0 leaves out some edge cells: 32 of 6,605 intersecting cells over 16 of the 99 units for this dekad, 12 of them holding paddy (ledger L160). Kota Pekalongan is one: 4 cells here, 6 cells with paddy in section 4.

4. A weight table: paddy hectares per cell

The weighted alternative needs, for each unit, the paddy area in each cell. Rice fields do not move between dekads, so this is computed once and stored. The first step is to know where each cell lies. A raster stores its georeference as the coordinates of its upper-left corner and the size of a cell (ST_UpperLeftX, ST_UpperLeftY, ST_ScaleX, ST_ScaleY); the scale in y is negative because rows count downward from the top. The skew values would turn the grid; they are 0 for a grid aligned with north, as here.

with connect() as conn:
    geo = conn.execute("""SELECT ST_UpperLeftX(rast), ST_UpperLeftY(rast), ST_ScaleX(rast), ST_ScaleY(rast),
                                 ST_Width(rast), ST_Height(rast), ST_SkewX(rast), ST_SkewY(rast)
                          FROM idx.chirps_dekad WHERE dekad_start = %s""", [DEKAD]).fetchone()
print(dict(zip(["x0", "y0", "dx", "dy", "columns", "rows", "skew_x", "skew_y"], geo)))
{'x0': 105.050004247576, 'y0': -5.000000968575478, 'dx': 0.05000000074505806, 'dy': -0.05000000074505806, 'columns': 225, 'rows': 76, 'skew_x': 0.0, 'skew_y': 0.0}

The corner and the cell size are not the round numbers 105.05, -5.0 and 0.05, though they differ from them by less than 0.00001 degree, about a metre on the ground. What matters is that every dekad raster carries exactly the same values (the checkpoint tests it), so the same arithmetic places a point in the same cell of every dekad.

With no skew, a point at longitude x and latitude y lies in column floor((x - x0) / dx) + 1 and row floor((y - y0) / dy) + 1; PostGIS counts columns and rows from 1 (ledger L161). Each field is placed in the cell that holds its inside point (ST_PointOnSurface, Chapter 5), and the fields are summed per unit, irrigation regime and cell. A field that straddles two cells goes wholly to one of them: against an exact intersection of fields and cells, this moves 1.5 to 3.1% of the paddy hectares to a neighbouring cell in four of the five kabupaten/kota tested, and 5.5% in the fifth, Kota Surabaya (ledger L41). The georeference is read from the first dekad raster.

The cell builds the table in about 10 seconds (ledger L159), adds a primary key and checks: each regime is irrigated or rainfed, each weight is above zero, and each kabupaten_code exists in ref.kabupaten (a foreign key). It runs in one transaction, so a failure leaves no half-built table behind.

PADDY_WEIGHT = """
CREATE TABLE idx.paddy_weight AS
WITH g AS (SELECT ST_UpperLeftX(rast) AS x0, ST_UpperLeftY(rast) AS y0,
                  ST_ScaleX(rast) AS dx, ST_ScaleY(rast) AS dy
           FROM idx.chirps_dekad ORDER BY dekad_start LIMIT 1),
     p AS (SELECT kabupaten_code, regime, area_ha, ST_PointOnSurface(geometry) AS pt
           FROM ref.paddy_moa2015)
SELECT p.kabupaten_code, p.regime,
       floor((ST_X(p.pt) - g.x0) / g.dx)::int + 1 AS col,
       floor((ST_Y(p.pt) - g.y0) / g.dy)::int + 1 AS row,
       sum(p.area_ha) AS ha
FROM p CROSS JOIN g
GROUP BY 1, 2, 3, 4"""

with connect() as conn:
    if conn.execute("SELECT to_regclass('idx.paddy_weight')").fetchone()[0]:
        print("idx.paddy_weight already exists: left as it is")
    else:
        t = time.perf_counter()
        conn.execute(PADDY_WEIGHT)
        conn.execute("""ALTER TABLE idx.paddy_weight
                        ADD PRIMARY KEY (kabupaten_code, regime, col, row),
                        ALTER COLUMN ha SET NOT NULL,
                        ADD CHECK (regime IN ('irrigated', 'rainfed')),
                        ADD CHECK (ha > 0),
                        ADD FOREIGN KEY (kabupaten_code) REFERENCES ref.kabupaten (code)""")
        geos = conn.execute("SELECT postgis_geos_version()").fetchone()[0]
        conn.execute(sql.SQL("COMMENT ON TABLE idx.paddy_weight IS {}").format(sql.Literal(
            "MoA 2015 paddy ha per kabupaten/kota, regime and CHIRPS cell (col, row of idx.chirps_dekad); fields "
            f"placed by ST_PointOnSurface (GEOS {geos}); built {dt.date.today()} by Chapter 6")))
        conn.execute("ANALYZE idx.paddy_weight")
        print(f"idx.paddy_weight built in {time.perf_counter() - t:.0f} s")
    rows, n_kab, n_cells = conn.execute("""SELECT count(*), count(DISTINCT kabupaten_code), count(DISTINCT (col, row))
                                           FROM idx.paddy_weight""").fetchone()
    n_insured = conn.execute("SELECT count(*) FROM idx.insured_unit").fetchone()[0]
print(f"{rows:,} rows | {n_kab} kabupaten/kota with paddy ({n_insured} insured units and {n_kab - n_insured} with less "
      f"paddy) | {n_cells:,} cells hold paddy")
idx.paddy_weight built in 10 s
7,002 rows | 116 kabupaten/kota with paddy (99 insured units and 17 with less paddy) | 4,184 cells hold paddy

The table covers every kabupaten/kota with paddy, not only the insured units: keeping the units with less rice lets you change the insured-unit rule of Chapter 5 later without rebuilding this table.

Look before moving on. Three checks on the table. The weights should add up to the whole paddy layer, since every field went to some cell; no weight should fall outside the raster (columns 1 to ST_Width, rows 1 to ST_Height); and no weight should sit in a cell that is nodata (sea), where there is no rainfall to weight. ST_PixelAsPoints(rast, 1, true) returns the cells of band 1 that have a value (true leaves out nodata) with their column x and row y, so NOT EXISTS finds weights without one.

with connect() as conn:
    check = conn.execute("""
        SELECT (SELECT sum(ha) FROM idx.paddy_weight) AS weights_ha,
               (SELECT sum(area_ha) FROM ref.paddy_moa2015) AS paddy_ha,
               (SELECT count(*) FROM idx.paddy_weight w, idx.chirps_dekad d
                WHERE d.dekad_start = %(d)s
                  AND (w.col NOT BETWEEN 1 AND ST_Width(d.rast) OR w.row NOT BETWEEN 1 AND ST_Height(d.rast)))
                  AS outside_raster,
               (SELECT count(*) FROM idx.paddy_weight w
                WHERE NOT EXISTS (SELECT 1 FROM idx.chirps_dekad d, LATERAL ST_PixelAsPoints(d.rast, 1, true) p
                                  WHERE d.dekad_start = %(d)s AND p.x = w.col AND p.y = w.row)) AS in_nodata
        """, {"d": DEKAD}).fetchone()
print(f"weights {check[0]:,.1f} ha | paddy layer {check[1]:,.1f} ha | outside the raster: {check[2]} | "
      f"in nodata cells: {check[3]}")
weights 3,391,572.1 ha | paddy layer 3,391,572.1 ha | outside the raster: 0 | in nodata cells: 0

PostGIS also has a function for the column and row of a point, ST_WorldToRasterCoord(rast, point). It should agree with the arithmetic. The next cell compares the two for every field of UNIT, and shows any field where they differ with its exact position in cell units (the column and row before floor) and its distance from the nearest cell edge, also in cells.

with connect() as conn:
    cmp = pd.DataFrame(conn.execute("""
        WITH d AS (SELECT rast FROM idx.chirps_dekad WHERE dekad_start = %(d)s),
             f AS (SELECT p.id, ST_PointOnSurface(p.geometry) AS pt FROM ref.paddy_moa2015 p
                   WHERE p.kabupaten_code = %(u)s)
        SELECT f.id, w.columnx AS col_postgis, w.rowy AS row_postgis,
               (ST_X(f.pt) - ST_UpperLeftX(d.rast)) / ST_ScaleX(d.rast) + 1 AS col_exact,
               (ST_Y(f.pt) - ST_UpperLeftY(d.rast)) / ST_ScaleY(d.rast) + 1 AS row_exact
        FROM f CROSS JOIN d, LATERAL ST_WorldToRasterCoord(d.rast, f.pt) AS w
        """, {"d": DEKAD, "u": UNIT}).fetchall(), columns=["id", "col_postgis", "row_postgis", "col_exact", "row_exact"])
differ = cmp[(cmp.col_postgis != np.floor(cmp.col_exact)) | (cmp.row_postgis != np.floor(cmp.row_exact))].copy()
differ["from_edge"] = np.minimum((differ.col_exact - differ.col_exact.round()).abs(),
                                 (differ.row_exact - differ.row_exact.round()).abs())
print(f"{len(cmp):,} fields in {unit_name}, {len(differ)} placed differently")
differ.style.format({"col_exact": "{:.9f}", "row_exact": "{:.9f}", "from_edge": "{:.1e}"})
31,527 fields in Garut, 2 placed differently
  id col_postgis row_postgis col_exact row_exact from_edge
15765 681571 52 51 52.059858972 50.999999981 1.9e-08
26268 705636 57 51 57.976187381 50.999999990 1.0e-08

Where the two differ, the inside point lies within a tiny fraction of a cell of the edge between two cells (from_edge). In the PostGIS source, ST_WorldToRasterCoord snaps a position that close to a whole number onto it, so the point lands in the next cell; the arithmetic always rounds down (ledger L161). Either choice is defensible for a point on a line. The weight table keeps the arithmetic, which is also faster: over the nearly one million fields, ST_WorldToRasterCoord took 40 s on the author’s computer, against about 10 s for building the whole weight table (ledger L159).

How many cells does a unit’s rainfall really rest on? A unit whose rice sits in one cell depends on that cell alone. The effective number of cells, (sum of ha)^2 / (sum of ha^2), equals the number of cells when all hold the same paddy area and falls towards 1 as the paddy concentrates in one cell.

with connect() as conn:
    eff = pd.DataFrame(conn.execute("""
        SELECT u.code, u.name, count(*) AS cells, round((sum(w.ha)^2 / sum(w.ha^2))::numeric, 1) AS effective_cells
        FROM (SELECT kabupaten_code, col, row, sum(ha) AS ha FROM idx.paddy_weight GROUP BY 1, 2, 3) w
        JOIN idx.insured_unit u ON u.code = w.kabupaten_code
        GROUP BY u.code, u.name ORDER BY effective_cells""").fetchall(),
                       columns=["code", "name", "cells", "effective_cells"])
eff["effective_cells"] = eff.effective_cells.astype(float)
print(f"effective cells per insured unit: median {eff.effective_cells.median():.1f}, "
      f"smallest {eff.effective_cells.min():.1f}, largest {eff.effective_cells.max():.1f}")
eff.head(5)
effective cells per insured unit: median 28.1, smallest 2.9, largest 89.6
code name cells effective_cells
0 3375 Kota Pekalongan 6 2.9
1 3575 Kota Pasuruan 4 3.0
2 3272 Kota Sukabumi 6 3.4
3 3574 Kota Probolinggo 6 3.4
4 3573 Kota Malang 8 3.8

Look before moving on. The units at the top of the list rest on a handful of cells: their index follows the rain of very few squares of about 5.5 km, and any error of the rainfall product in those cells goes straight into the index. A median unit averages over many more.

The map shows the weights of UNIT: each cell shaded by the paddy hectares it holds, for both regimes together. The cell squares come from ST_PixelAsPolygons again, joined to the weights on column and row.

weights = gpd.read_postgis("""
    SELECT p.x AS col, p.y AS row, w.ha, p.geom
    FROM (SELECT col, row, sum(ha) AS ha FROM idx.paddy_weight WHERE kabupaten_code = %(u)s GROUP BY 1, 2) w
    JOIN (SELECT q.x, q.y, q.geom FROM idx.chirps_dekad d, LATERAL ST_PixelAsPolygons(d.rast, 1, false) q
          WHERE d.dekad_start = %(d)s) p ON p.x = w.col AND p.y = w.row""", ENGINE, geom_col="geom",
                           params={"u": UNIT, "d": DEKAD})
unit_ha = pd.read_sql("SELECT paddy_ha FROM idx.insured_unit WHERE code = %(u)s", ENGINE, params={"u": UNIT}).paddy_ha[0]
fig, ax = plt.subplots(figsize=(7, 6))
weights.plot(ax=ax, column="ha", cmap="Greens", edgecolor="0.6", linewidth=0.3, legend=True,
             legend_kwds={"label": "paddy ha in the cell", "shrink": 0.7})
unit.boundary.plot(ax=ax, color="black", linewidth=0.8)
ax.set_title(f"{unit_name}: {len(weights)} cells with paddy, {weights.ha.sum():,.0f} ha")
ax.set_axis_off()
plt.show()
print(f"weights {weights.ha.sum():,.1f} ha | paddy_ha in idx.insured_unit {float(unit_ha):,.1f} ha")

Map of Kabupaten Garut where each rainfall cell is shaded by the hectares of paddy it holds, from none to the most, with the unit boundary in black.

weights 45,097.1 ha | paddy_ha in idx.insured_unit 45,097.1 ha

Look before moving on. The hectares in the title should equal the unit’s paddy_ha (printed under the map). Cells cut by the boundary can hold weights too: a field near the edge has its inside point in a cell whose centre may lie outside the unit, a cell the centre rule of section 3 would not count.

5. Dekad rainfall for every unit

With the weights in place, the paddy-weighted rainfall of a unit in a dekad is sum(rain x ha) / sum(ha) over the unit’s cells. ST_PixelAsPoints turns every dekad raster into rows of (column, row, value), and a join on column and row brings the weights to them. Before building the whole table, the next cell times three ways to compute one year of dekads (2019, 36 dekads) for the insured units:

  • clip: ST_Clip and ST_SummaryStats per unit and dekad, centre rule, no weights (section 3);
  • value: ST_Value(rast, 1, col, row), one call per weight row and dekad;
  • join: ST_PixelAsPoints once per dekad, then an ordinary join to the weights.

In each query the CTE w adds the two regimes of a cell together, so every cell has one weight per unit. The value method leaves out a cell whose value is nodata (ST_Value returns NULL there) from both the rain and the hectares, as the join does by having no row for it. Each method returns a dekad mean per unit; the cell adds them up to 2019 totals, kept in year_total for section 7. sum(min_count=36) makes a total empty unless all 36 dekads have a value, so Kota Pasuruan’s clip total stays empty instead of 0. The cell takes about a minute, most of it the clip method (ledger L159).

YEAR = {"y0": "2019-01-01", "y1": "2020-01-01"}
METHODS = {
    "clip": """
        SELECT u.code, d.dekad_start, (ST_SummaryStats(ST_Clip(d.rast, k.geometry))).mean
        FROM idx.insured_unit u JOIN ref.kabupaten k ON k.code = u.code
        JOIN idx.chirps_dekad d ON d.dekad_start >= %(y0)s AND d.dekad_start < %(y1)s""",
    "value": """
        WITH w AS (SELECT kabupaten_code, col, row, sum(ha) AS ha FROM idx.paddy_weight GROUP BY 1, 2, 3)
        SELECT w.kabupaten_code, d.dekad_start, sum(v.val * w.ha) / sum(w.ha)
        FROM w
        JOIN idx.insured_unit u ON u.code = w.kabupaten_code
        JOIN idx.chirps_dekad d ON d.dekad_start >= %(y0)s AND d.dekad_start < %(y1)s
        CROSS JOIN LATERAL (SELECT ST_Value(d.rast, 1, w.col, w.row) AS val) v
        WHERE v.val IS NOT NULL
        GROUP BY 1, 2""",
    "join": """
        WITH w AS (SELECT kabupaten_code, col, row, sum(ha) AS ha FROM idx.paddy_weight GROUP BY 1, 2, 3)
        SELECT w.kabupaten_code, p.dekad_start, sum(p.val * w.ha) / sum(w.ha)
        FROM w
        JOIN idx.insured_unit u ON u.code = w.kabupaten_code
        JOIN (SELECT d.dekad_start, q.x AS col, q.y AS row, q.val
              FROM idx.chirps_dekad d, LATERAL ST_PixelAsPoints(d.rast, 1, true) q
              WHERE d.dekad_start >= %(y0)s AND d.dekad_start < %(y1)s) p
          ON p.col = w.col AND p.row = w.row
        GROUP BY 1, 2""",
}
year_total, timing = {}, {}
with connect() as conn:
    for name, query in METHODS.items():
        t = time.perf_counter()
        rows = pd.DataFrame(conn.execute(query, YEAR).fetchall(), columns=["code", "dekad_start", "mm"])
        timing[name] = time.perf_counter() - t
        year_total[name] = rows.groupby("code").mm.sum(min_count=36)
        print(f"{name:6s} {len(rows):,} unit-dekads in {timing[name]:.1f} s")
print(f"join vs value: largest difference {(year_total['join'] - year_total['value']).abs().max():.1e} mm a year")
clip   3,564 unit-dekads in 41.6 s
value  3,564 unit-dekads in 28.1 s
join   3,564 unit-dekads in 0.9 s
join vs value: largest difference 1.4e-12 mm a year

Look before moving on. The value and join methods compute the same weighted mean, so their totals should agree to rounding. On the author’s computer the join took under a second for the year, the value method about 28 s and clipping about 42 s (ledger L159); your times will differ, the order should not. The join reads each dekad raster once, where the value method calls a function per weight row and dekad, and clipping builds a new raster for every unit and dekad.

The full table uses the join over all dekads and for three regimes: all (every paddy field), irrigated and rainfed, so that rainfed rice can be followed on its own (the index of later chapters uses all). The weights for all are the two regimes added per cell (GROUP BY 1, 3, 4 groups on unit, column and row; position 2 is the constant 'all'), appended to the regime weights with UNION ALL. JOIN px USING (col, row) joins on the columns of the same name in both. ha_used records the paddy area behind each value. The build takes about a minute (ledger L159) and prints nothing until it ends.

DEKAD_RAIN = """
CREATE TABLE idx.dekad_rain AS
WITH px AS (SELECT d.dekad_start, p.x AS col, p.y AS row, p.val
            FROM idx.chirps_dekad d, LATERAL ST_PixelAsPoints(d.rast, 1, true) p),
     w AS (SELECT kabupaten_code, regime, col, row, ha FROM idx.paddy_weight
           UNION ALL
           SELECT kabupaten_code, 'all', col, row, sum(ha) FROM idx.paddy_weight GROUP BY 1, 3, 4)
SELECT w.kabupaten_code, w.regime, px.dekad_start,
       sum(px.val * w.ha) / sum(w.ha) AS mm, sum(w.ha) AS ha_used
FROM w JOIN px USING (col, row)
GROUP BY 1, 2, 3"""

with connect() as conn:
    if conn.execute("SELECT to_regclass('idx.dekad_rain')").fetchone()[0]:
        print("idx.dekad_rain already exists: left as it is")
    else:
        t = time.perf_counter()
        conn.execute(DEKAD_RAIN)
        conn.execute("""ALTER TABLE idx.dekad_rain
                        ADD PRIMARY KEY (kabupaten_code, regime, dekad_start),
                        ALTER COLUMN mm SET NOT NULL,
                        ALTER COLUMN ha_used SET NOT NULL,
                        ADD CHECK (regime IN ('all', 'irrigated', 'rainfed')),
                        ADD CHECK (ha_used > 0)""")
        conn.execute(sql.SQL("COMMENT ON TABLE idx.dekad_rain IS {}").format(sql.Literal(
            "Paddy-weighted dekad rainfall (mm) per kabupaten/kota and regime (all, irrigated, rainfed) from "
            f"idx.chirps_dekad and idx.paddy_weight; ha_used = paddy ha behind the value; built {dt.date.today()} "
            "by Chapter 6")))
        conn.execute("ANALYZE idx.dekad_rain")
        print(f"idx.dekad_rain built in {time.perf_counter() - t:.0f} s")
    summary = conn.execute("""
        SELECT count(*), count(DISTINCT kabupaten_code), min(dekad_start), max(dekad_start),
               pg_size_pretty(pg_total_relation_size('idx.dekad_rain'))
        FROM idx.dekad_rain""").fetchone()
    per_regime = dict(conn.execute("""SELECT regime, count(DISTINCT kabupaten_code) FROM idx.dekad_rain
                                      GROUP BY regime ORDER BY regime""").fetchall())
    per_unit = conn.execute("""
        SELECT min(n), max(n) FROM (SELECT u.code, count(r.dekad_start) AS n
                                    FROM idx.insured_unit u
                                    LEFT JOIN idx.dekad_rain r ON r.kabupaten_code = u.code AND r.regime = 'all'
                                    GROUP BY u.code) s""").fetchone()
    n_dekads = conn.execute("SELECT count(*) FROM idx.chirps_dekad").fetchone()[0]
print(dict(zip(["rows", "kabupaten", "first_dekad", "last_dekad", "size"], summary)))
print("kabupaten/kota per regime:", per_regime)
print(f"dekads per insured unit (regime all): {per_unit[0]} to {per_unit[1]}, of {n_dekads} dekad rasters")
idx.dekad_rain built in 46 s
{'rows': 531981, 'kabupaten': 116, 'first_dekad': datetime.date(1981, 1, 1), 'last_dekad': datetime.date(2026, 9, 21), 'size': '52 MB'}
kabupaten/kota per regime: {'all': 116, 'irrigated': 116, 'rainfed': 91}
dekads per insured unit (regime all): 1647 to 1647, of 1647 dekad rasters

Look before moving on. Every insured unit should have a value for every dekad raster. Every kabupaten/kota with paddy has all and irrigated rows; fewer have rainfed rows, because a unit whose paddy is all irrigated has no rainfed fields.

A row of the table is easy to read back. The query below takes the dekad DEKAD for UNIT: the all value should lie between the two regimes, and its ha_used should be the sum of theirs.

pd.read_sql("""SELECT kabupaten_code, regime, dekad_start, round(mm::numeric, 2) AS mm, round(ha_used::numeric) AS ha_used
               FROM idx.dekad_rain WHERE kabupaten_code = %(u)s AND dekad_start = %(d)s ORDER BY regime""",
            ENGINE, params={"u": UNIT, "d": DEKAD})
kabupaten_code regime dekad_start mm ha_used
0 3205 all 2019-01-11 227.99 45097.0
1 3205 irrigated 2019-01-11 224.98 22949.0
2 3205 rainfed 2019-01-11 231.11 22148.0

6. Check against numpy

A result the database computed in one large query deserves a check by other means. The cell reads the dekad raster DEKAD back as a GeoTIFF (ST_AsGDALRaster, as in Chapter 4) into a numpy array, takes the weights as a plain table, and computes the weighted mean of every unit and regime in numpy: the value at [row - 1, col - 1] (numpy counts from 0) times the hectares, summed and divided by the hectares. It then compares the result with idx.dekad_rain. It checks one dekad; change DEKAD in the setup cell to check another.

with connect() as conn:
    tif = conn.execute("SELECT ST_AsGDALRaster(rast, 'GTiff') FROM idx.chirps_dekad WHERE dekad_start = %s",
                       [DEKAD]).fetchone()[0]
    w = pd.DataFrame(conn.execute("SELECT kabupaten_code, regime, col, row, ha FROM idx.paddy_weight").fetchall(),
                     columns=["code", "regime", "col", "row", "ha"])
    db = pd.DataFrame(conn.execute("SELECT kabupaten_code, regime, mm FROM idx.dekad_rain WHERE dekad_start = %s",
                                   [DEKAD]).fetchall(), columns=["code", "regime", "mm"])
with MemoryFile(bytes(tif)) as mem, mem.open() as src:
    rain = src.read(1).astype("float64")
    nodata = src.nodata

w = pd.concat([w, w.groupby(["code", "col", "row"], as_index=False).ha.sum().assign(regime="all")])
w["rain"] = rain[w["row"].to_numpy() - 1, w["col"].to_numpy() - 1]
print("weights on a nodata cell:", int((w.rain == nodata).sum()))
w["rain_x_ha"] = w.rain * w.ha
by_numpy = w.groupby(["code", "regime"]).agg(rain_x_ha=("rain_x_ha", "sum"), ha=("ha", "sum"))
by_numpy["mm_numpy"] = by_numpy.rain_x_ha / by_numpy.ha
both = db.set_index(["code", "regime"]).join(by_numpy.mm_numpy, how="outer")
print(f"{len(both)} unit-regime values for {DEKAD}, {both.isna().any(axis=1).sum()} missing on one side, "
      f"largest difference {(both.mm - both.mm_numpy).abs().max():.1e} mm")
weights on a nodata cell: 0
323 unit-regime values for 2019-01-11, 0 missing on one side, largest difference 2.0e-13 mm

Look before moving on. No value should be missing on either side, and the differences should be at the level of floating-point rounding, far below a tenth of a millimetre. A difference of whole millimetres would point to cells shifted by one column or row.

7. What the weighting changes

This section uses year_total from the timing cell of section 5; run that cell first if you restarted the kernel. The clip totals give every cell whose centre lies in the unit the same weight; the join totals weight each cell by its paddy, edge cells included. The cell compares them per insured unit: the difference in percent, a scatter plot, and whether the order of the units from dry to wet stays the same (a rank correlation).

# column names clip_mm and weighted_mm: a DataFrame already has a method called clip
cmp2019 = pd.DataFrame({"clip_mm": year_total["clip"], "weighted_mm": year_total["join"]}).astype(float)
cmp2019["diff_pct"] = 100 * (cmp2019.weighted_mm - cmp2019.clip_mm) / cmp2019.clip_mm
both_ok = cmp2019.dropna()
print(f"2019 totals: {len(cmp2019)} units, {cmp2019.clip_mm.isna().sum()} without a clip value; "
      f"|difference| median {both_ok.diff_pct.abs().median():.1f}%, largest {both_ok.diff_pct.abs().max():.1f}%; "
      f"rank correlation {both_ok.clip_mm.corr(both_ok.weighted_mm, method='spearman'):.3f}")
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(both_ok.clip_mm, both_ok.weighted_mm, s=12)
lim = [both_ok[["clip_mm", "weighted_mm"]].min().min() * 0.95, both_ok[["clip_mm", "weighted_mm"]].max().max() * 1.05]
ax.plot(lim, lim, color="0.5", linewidth=0.8)
ax.set_xlabel("2019 rainfall, clip (mm)"); ax.set_ylabel("2019 rainfall, paddy-weighted (mm)")
plt.show()
names = pd.read_sql("SELECT code, name FROM idx.insured_unit", ENGINE).set_index("code")
cmp2019.join(names).reindex(cmp2019.diff_pct.abs().sort_values(ascending=False, na_position="first").index).head(5).round(1)
2019 totals: 99 units, 1 without a clip value; |difference| median 3.2%, largest 27.9%; rank correlation 0.972

Scatter plot of 2019 rainfall per insured unit, unweighted clip total against paddy-weighted total, with most points near the one-to-one line and the points far from it below the line.

clip_mm weighted_mm diff_pct name
code
3575 NaN 1191.4 NaN Kota Pasuruan
3513 2062.0 1487.4 -27.9 Probolinggo
3512 1315.8 1037.2 -21.2 Situbondo
3579 2827.3 2346.9 -17.0 Kota Batu
3204 2656.1 2250.8 -15.3 Bandung

Look before moving on. For most units the two totals are close (compare the median difference with the largest), and the rank correlation near 1 says the order of the units from dry to wet hardly changes. The units at the top of the table are the exceptions: in them the paddy-weighted total is well below the clip total, so their rice lies in drier parts of the unit, or in edge cells the centre rule leaves out. Kota Pasuruan, which the clip leaves without rainfall, heads the list. An index is paid unit by unit, so it is those units that decide whether the weight table is worth having.

Within a unit the regimes can differ too. The figure shows the mean rainfall of each dekad of the year for UNIT, by regime, over 1991-2020, the reference period of the drought index (Chapter 8). It plots millimetres per day (the dekad total divided by n_days), because the last dekad of a month has 8 to 11 days (Chapter 4) and its total would otherwise jump with the length of the month. The dekad of the year (1 to 36) comes from the month and the day of dekad_start. The table under it gives the mean yearly total of each regime.

clim = pd.read_sql("""
    SELECT r.regime, (extract(month FROM r.dekad_start)::int - 1) * 3
                     + CASE WHEN extract(day FROM r.dekad_start) = 1 THEN 1
                            WHEN extract(day FROM r.dekad_start) = 11 THEN 2 ELSE 3 END AS dekad_of_year,
           avg(r.mm / d.n_days) AS mm_per_day, avg(r.mm) AS mm
    FROM idx.dekad_rain r JOIN idx.chirps_dekad d USING (dekad_start)
    WHERE r.kabupaten_code = %(u)s AND r.dekad_start >= '1991-01-01' AND r.dekad_start < '2021-01-01'
    GROUP BY 1, 2 ORDER BY 1, 2""", ENGINE, params={"u": UNIT})
fig, ax = plt.subplots(figsize=(9, 3.5))
for regime, g in clim.groupby("regime"):
    ax.plot(g.dekad_of_year, g.mm_per_day, label=regime)
ax.set_xticks([1 + 3 * m for m in range(12)], ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"])
ax.set_xlabel("dekad of the year"); ax.set_ylabel("mean rainfall 1991-2020 (mm/day)")
ax.set_title(unit_name); ax.legend()
plt.show()
clim.groupby("regime").mm.sum().round(0).rename("mean yearly total 1991-2020 (mm)").to_frame()

Line chart of mean daily rainfall per dekad 1991-2020 in Kabupaten Garut over the 36 dekads of the year, one line each for all paddy, irrigated and rainfed paddy.

mean yearly total 1991-2020 (mm)
regime
all 2847.0
irrigated 2647.0
rainfed 3054.0

Look before moving on. Compare the yearly totals: in this unit the rainfed fields lie where it rains more than over the irrigated ones, and the lines show in which months the gap is largest. In the 99 insured units, most of the drought damage reported in 2016-2025 fell in April to September (ledger L49): in this unit the lines fall from April and are lowest from June to September; Chapter 7 sets the rice seasons against this cycle.

Checkpoint

The cell below checks, in a new session, what Chapter 7 relies on: dekad rasters that all share one grid (the corner, cell size and dimensions on which the column and row arithmetic rests); weights that add up to the paddy layer; the primary keys; in idx.dekad_rain, a value for every insured unit and every dekad raster, no invalid millimetres (NaN, infinity or below 0), the weights of every unit behind every one of its all rows, and all equal to irrigated plus rainfed. It depends only on the setup cell.

with connect() as conn:
    first_row = lambda q, p=None: conn.execute(q, p).fetchone()
    grids = first_row("""SELECT count(DISTINCT (ST_UpperLeftX(rast), ST_UpperLeftY(rast), ST_ScaleX(rast), ST_ScaleY(rast),
                                                ST_Width(rast), ST_Height(rast))) FROM idx.chirps_dekad""")[0]
    w_ha, p_ha = first_row("SELECT (SELECT sum(ha) FROM idx.paddy_weight), (SELECT sum(area_ha) FROM ref.paddy_moa2015)")
    keys = first_row("""SELECT count(*) FROM pg_constraint WHERE contype = 'p'
                        AND conrelid IN ('idx.paddy_weight'::regclass, 'idx.dekad_rain'::regclass)""")[0]
    n_dekads = first_row("SELECT count(*) FROM idx.chirps_dekad")[0]
    incomplete = first_row("""SELECT count(*) FROM idx.insured_unit u
                              WHERE (SELECT count(*) FROM idx.dekad_rain r
                                     WHERE r.kabupaten_code = u.code AND r.regime = 'all') <> %s""", [n_dekads])[0]
    bad = first_row("""SELECT count(*) FROM idx.dekad_rain
                       WHERE mm = 'NaN'::float8 OR mm = 'Infinity'::float8 OR mm < 0""")[0]
    gap = first_row("""SELECT count(*)
                       FROM (SELECT kabupaten_code, sum(ha) AS ha FROM idx.paddy_weight GROUP BY 1) w
                       LEFT JOIN (SELECT kabupaten_code, min(ha_used) AS lo, max(ha_used) AS hi FROM idx.dekad_rain
                                  WHERE regime = 'all' GROUP BY 1) r USING (kabupaten_code)
                       WHERE r.lo IS NULL OR abs(w.ha - r.lo) > 0.01 OR abs(w.ha - r.hi) > 0.01""")[0]
    regimes = first_row("""SELECT count(*) FROM idx.dekad_rain a
                           JOIN (SELECT kabupaten_code, dekad_start, sum(ha_used) AS ha, sum(mm * ha_used) AS mm_ha
                                 FROM idx.dekad_rain WHERE regime <> 'all' GROUP BY 1, 2) s USING (kabupaten_code, dekad_start)
                           WHERE a.regime = 'all'
                             AND (abs(a.ha_used - s.ha) > 1e-6 OR abs(a.mm * a.ha_used - s.mm_ha) > 1e-3)""")[0]

assert grids == 1, f"idx.chirps_dekad holds {grids} different grids"
assert abs(w_ha - p_ha) < 0.01, f"weights {w_ha:,.2f} ha, paddy layer {p_ha:,.2f} ha"
assert keys == 2, f"primary keys found: {keys}"
assert incomplete == 0 and bad == 0, f"units without every dekad: {incomplete}; invalid mm: {bad}"
assert gap == 0 and regimes == 0, f"units whose weights are not behind every dekad: {gap}; all <> irrigated + rainfed: {regimes}"
print(f"checkpoint passed: {n_dekads} dekads on one grid for every insured unit, weights {w_ha:,.0f} ha; "
      f"code cells took {time.perf_counter() - T0:.0f} s since the setup cell")
checkpoint passed: 1647 dekads on one grid for every insured unit, weights 3,391,572 ha; code cells took 152 s since the setup cell

Troubleshooting

Symptom Cause Fix
... is missing: run Chapters 3 to 5 first an earlier chapter has not been run run that chapter first
UNIT ... is not an insured unit or DEKAD ... is not the first day of a dekad a setting in the setup cell changed use a code from idx.insured_unit, and a date on the 1st, 11th or 21st of a month from 1981 to September 2026
function st_clip(raster, geometry, touched => boolean) does not exist PostGIS older than 3.5 upgrade PostGIS, or remove the touched line from the query in section 3
NameError: name 'year_total' is not defined (or unit, unit_name) the kernel was restarted, or a cell skipped run the setup cell, then the timing cell of section 5, before section 7
numpy check: differences of whole millimetres weights shifted by a column or row check the georeference printed in section 4 against Chapter 4’s raster
idx.paddy_weight already exists, but ref.paddy_moa2015 has changed the cells never drop a table that later chapters use DROP TABLE idx.dekad_rain, idx.paddy_weight in a new cell, then run sections 4 and 5 again

Summary

You now have:

  • idx.paddy_weight: the paddy hectares of each kabupaten/kota and irrigation regime in each rainfall cell, the link between the vector fields and the raster grid;
  • idx.dekad_rain: paddy-weighted rainfall for every kabupaten/kota with paddy, regime and dekad from 1981 to September 2026, with one dekad checked against numpy.

On the way you saw that a raster summary over a polygon depends on which cells it counts, that a function can count differently from what its description leads you to expect, and that a stored weight table turns a raster-vector problem into an ordinary join.

What comes next

Chapter 7 decides when the rice grows in each unit: it sets out a crop calendar with growth stages, so that the dekad rainfall of this chapter can be read against the stage of the crop.

References