Skip to main content

Chapter 4: Daily rainfall as rasters

Chapter 4: Daily rainfall as rasters

TipAt a glance
  • You will build: raw.chirps_rnl_daily (one raster per day, 1981 to September 2026), idx.chirps_dekad (ten-day rainfall totals) and idx.data_status (what is final and what may still change)
  • You need: Chapters 2 and 3; an internet connection on the first run; 46 files (about 385 MB) to download into data_dir; about 0.5 GB of space in the database; raster2pgsql from the PostGIS bundle
  • Time to run: About 11 minutes once the files are in data_dir (the checkpoint prints the time), most of it loading in section 4; the first run also downloads about 385 MB
  • Level: Intermediate

A rainfall index needs rainfall for every insured unit and every season, over many years. In this chapter you load daily rainfall for Java from 1981 to September 2026 into the database as rasters, one grid per day, and add the days up to ten-day totals (dekads) inside the database, the time step of the index in later chapters. Along the way you check the data against the producer’s own files, and you record which part of the record is final and which part the producer may still revise.

NoteLearning objectives

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

  • explain how PostGIS stores a raster (a grid in one column of one row, with bands, a pixel type, nodata and a coordinate system) and when to cut a raster into tiles;
  • load GeoTIFFs with raster2pgsql, one row per file, and add raster constraints;
  • check a loaded raster against an independent reading of the same file, and the file against its producer;
  • add rasters up across rows with ST_Union(rast, 'SUM') and GROUP BY;
  • record which part of a dataset is final, so that later results can mark what may still change.

Before running this chapter:

  • complete Chapter 2 and Chapter 3: section 6 draws the provinces of Chapter 3, and section 7 reads the update date of its damage reports;
  • check pg_bin in config.yml: on Windows the bin folder of your PostgreSQL installation, which holds raster2pgsql.exe from the PostGIS bundle (ledger L16); on macOS and Linux null, if raster2pgsql is on your PATH;
  • be online for the first run, which downloads 46 files (about 385 MB) into data_dir; later runs find them there;
  • allow about 10 minutes for section 4, which writes about 0.5 GB into the database and prints a line per year. You can interrupt it and run it again: years already loaded are skipped.

1. Setup

The setup cell reads config.yml, defines connect() and ENGINE as in Chapter 3, checks that the tables of Chapter 3 are there, and finds raster2pgsql.

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

import datetime as dt
import hashlib
import shutil
import subprocess
import tempfile
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 rasterio
import requests
import yaml
from rasterio.io import MemoryFile
from sqlalchemy import URL, create_engine

T0 = time.perf_counter()
# rasterio 1.5 with numpy 2.5 warns on every read about a numpy change; the warning does not affect the values
warnings.filterwarnings("ignore", category=DeprecationWarning, message="Setting the shape on a NumPy array")

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

PG_BIN = Path(CONFIG["pg_bin"]) if CONFIG.get("pg_bin") else None
RASTER2PGSQL = shutil.which("raster2pgsql", path=str(PG_BIN) if PG_BIN else None)
if RASTER2PGSQL is None:
    raise FileNotFoundError("raster2pgsql not found: set pg_bin in config.yml to the folder that holds it")

with connect() as conn:
    print("connected |", conn.execute("SELECT postgis_full_version()").fetchone()[0][:60], "...")
    print("from Chapter 3: ref.province", conn.execute("SELECT count(*) FROM ref.province").fetchone()[0], "rows,",
          "raw.datanonkom_damage", f"{conn.execute('SELECT count(*) FROM raw.datanonkom_damage').fetchone()[0]:,} rows")
print("raster2pgsql:", RASTER2PGSQL)
connected | POSTGIS="3.7.0 3.7.0" [EXTENSION] PGSQL="180" GEOS="3.15.1-C ...
from Chapter 3: ref.province 6 rows, raw.datanonkom_damage 696,150 rows
raster2pgsql: C:\Program Files\PostgreSQL\18\bin\raster2pgsql.EXE

2. The rainfall data

The rainfall comes from CHIRPS v3.0, produced by the Climate Hazards Center (CHC) at UC Santa Barbara. It covers the land between 60 N and 60 S at 0.05 degree, about 5.5 km in Java (ledger L146), from 1981 to near-present (ledger L27). CHC’s page states both a CC BY 4.0 licence and a waiver of copyright (ledger L27); this series follows CC BY 4.0 and credits CHC.

CHIRPS is built as a pentad (five-day) and monthly product. Its daily values split each pentad total over the days in proportion to the daily rain of another dataset (ledger L27, ledger L28). Two daily versions exist: rnl splits by ERA5, a reconstruction of past weather by the European Centre for Medium-Range Weather Forecasts, and starts in 1981; sat splits by IMERG satellite rainfall and starts in 1998 (ledger L28). This series uses rnl because it covers the whole record from 1981; where both exist, their dekad totals are the same (checked for 2016 to 2025, ledger L32).

The series ships a Java extract: one GeoTIFF per year with one band per day (ledger L148), on CHC’s own grid without resampling (ledger L35). A GeoTIFF can hold several bands, layers of values on the same grid; here band 1 is 1 January, band 2 is 2 January, and so on. The days up to September 2025 come from an export of CHIRPS through Google Earth Engine (ledger L10), the later days straight from CHC (ledger L36, ledger L37); section 3 checks the export against CHC. The next cell downloads the years that are not in data_dir yet and checks each file against the checksum list in the repository.

YEARLY = DATA / "chirps" / "java_yearly"
YEARLY.mkdir(parents=True, exist_ok=True)
# each line of the checksum file reads "sha256  filename"
expected = {name: sha for sha, name in
            (line.split() for line in (ROOT / CONFIG["chirps"]["checksums"]).read_text().splitlines())}

t = time.perf_counter()
for name, sha in sorted(expected.items()):
    path = YEARLY / name
    if not path.exists():
        part = path.with_suffix(".part")
        with requests.get(CONFIG["chirps"]["url"].format(file=name), 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)
        print(f"downloaded {name} ({path.stat().st_size / 1e6:.1f} MB)")
    if hashlib.sha256(path.read_bytes()).hexdigest() != sha:
        raise ValueError(f"{name}: checksum does not match; delete the file and run the cell again")
size = sum((YEARLY / n).stat().st_size for n in expected) / 1e6
print(f"{len(expected)} files, {size:.1f} MB, all checksums match ({time.perf_counter() - t:.0f} s)")
46 files, 385.4 MB, all checksums match (1 s)

Look before moving on. Open one year and read what the file says about itself: its coordinate system, its grid (the transform gives the top-left corner and the cell size), its size, its nodata value (the number that stands for “no value”, here the sea), and the names of its first and last bands. A wrong file would show itself here: no CRS, one band instead of 365, or band names of another year.

with rasterio.open(YEARLY / "chirps-v3.0-rnl-java-2019.tif") as src:
    print("CRS:", src.crs, "| cell size:", src.res, "| top-left corner:", (src.transform.c, src.transform.f))
    print("size:", src.width, "x", src.height, "cells |", src.count, "bands |", src.dtypes[0], "| nodata:", src.nodata)
    print("bands:", src.descriptions[0], "...", src.descriptions[-1])
    print("tags:", src.tags())
    jan1 = src.read(1, masked=True)
print(f"1 January 2019: {jan1.count():,} land cells, mean {jan1.mean():.1f} mm, max {jan1.max():.1f} mm")
CRS: EPSG:4326 | cell size: (0.05000000074505806, 0.05000000074505806) | top-left corner: (105.050004247576, -5.000000968575478)
size: 225 x 76 cells | 365 bands | float32 | nodata: -9999.0
bands: d20190101 ... d20191231
tags: {'AREA': 'Java window 105.05-116.30 E, 8.80-5.00 S, source grid', 'LICENSE': 'CC BY 4.0', 'PREPARED': 'postgis-crop-insurance tutorial, 2026-12-01', 'SOURCE': 'CHIRPS v3.0 daily rnl (Climate Hazards Center, UC Santa Barbara), doi:10.15780/G2JQ0P', 'UNITS': 'mm/day', 'AREA_OR_POINT': 'Area'}
1 January 2019: 6,674 land cells, mean 11.0 mm, max 45.1 mm

Each band is a grid of 225 by 76 cells. The cell size and corner end in long decimals because CHC’s 0.05-degree grid is stored as binary floating-point numbers; the grid is CHC’s own (ledger L147). The window is a rectangle around Java, so it also takes in the southern tip of Sumatra, Bali and part of Lombok: of its 6,674 land cells, 4,329 have their centre in Java (ledger L150). Chapter 6 uses only the cells under rice fields. The file’s tags carry the source and licence with the data.

3. Check one day against the producer

A copy is only as good as its last check against the source. CHC also publishes its final daily grids as cloud-optimised GeoTIFFs (COGs, ledger L37): GeoTIFFs stored in tiles, fixed-size blocks of the grid, with an index of the blocks at the start of the file, so that a program can read part of the file over the web with HTTP range requests (requests for some bytes of a file) instead of downloading all of it (GDAL COG driver). Reading the Java window of one day this way takes two requests and about 0.4 MB instead of a file of about 15 to 25 MiB (ledger L37). GDAL is the open-source library that reads and writes raster files for rasterio, QGIS and PostGIS; it reads a file over the web when its path starts with /vsicurl/ (GDAL virtual file systems).

The cell reads one day, 15 January 2019 (any day would do), from CHC, keeps the result in data_dir so that later runs need no request, and compares it with band 15 of the 2019 file. Delete the saved file in data_dir/chirps/chc_check to check against CHC again.

DAY = dt.date(2019, 1, 15)
COG = ("https://data.chc.ucsb.edu/products/CHIRPS/v3.0/daily/final/rnl/cogs/"
       f"{DAY.year}/chirps-v3.0.rnl.{DAY:%Y.%m.%d}.cog")
saved = DATA / "chirps" / "chc_check" / f"chc_{DAY:%Y%m%d}.npy"

with rasterio.open(YEARLY / f"chirps-v3.0-rnl-java-{DAY.year}.tif") as src:
    band = (DAY - dt.date(DAY.year, 1, 1)).days + 1
    ours, grid, nodata = src.read(band), src.transform, src.nodata
    assert src.descriptions[band - 1] == f"d{DAY:%Y%m%d}"

if not saved.exists():
    env = dict(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR",   # do not list CHC's folder first: saves requests
               GDAL_HTTP_USERAGENT="Mozilla/5.0 (compatible; postgis-crop-insurance tutorial)")   # say who asks
    with rasterio.Env(**env), rasterio.open("/vsicurl/" + COG) as chc:
        # where our window starts on CHC's global grid, in columns and rows
        col0 = round((grid.c - chc.transform.c) / chc.transform.a)
        row0 = round((grid.f - chc.transform.f) / chc.transform.e)
        window = chc.read(1, window=((row0, row0 + ours.shape[0]), (col0, col0 + ours.shape[1])))
    saved.parent.mkdir(parents=True, exist_ok=True)
    np.save(saved, window)
theirs = np.load(saved)

land = ours != nodata
print(COG)
print("same land cells:", bool((land == (theirs != -9999)).all()), "|", int(land.sum()), "land cells",
      "| largest difference:", float(np.abs(ours[land] - theirs[land]).max()), "mm")
https://data.chc.ucsb.edu/products/CHIRPS/v3.0/daily/final/rnl/cogs/2019/chirps-v3.0.rnl.2019.01.15.cog
same land cells: True | 6674 land cells | largest difference: 0.0 mm

Look before moving on. The land cells are the same and the values are identical, to the last bit of a 32-bit float. CHC’s file stores the sea as -9999 too, but does not declare it as its nodata value (ledger L147), so the cell compares the land masks explicitly. The same test gives the same answer for 1 June 1985 (ledger L147). A difference here would most likely mean that CHC has re-released the data since the files of this series were made (section 7).

4. Rasters in PostGIS

PostGIS stores a raster as one value in one column, of type raster: a grid with its position (the coordinates of its top-left corner and its cell size), its coordinate system (SRID), and one or more bands. Each band has a pixel type (32BF, a 32-bit float, for rainfall) and a nodata value. One row holds one complete raster.

How much of a dataset goes into one row is a design choice:

  • one row per day, the whole window in each: 16,709 small rows, each found by its date. This series’ choice;
  • one row per year, 365 or 366 bands in each: fewer rows, but reading one day means decoding the whole year’s raster, about 33 ms per band (ledger L148);
  • tiles: raster2pgsql -t 100x100 cuts each grid into pieces, one row each. Tiling pays off for large grids, where a query about a small area can skip most tiles through a spatial index. A day here is 225 x 76 cells and every question in this series covers the whole window, so the series does not tile.

raster2pgsql, which comes with the PostGIS bundle, turns raster files into SQL: one INSERT per file, with the raster written out as hexadecimal text in PostGIS’s raster format. Its options used here:

option meaning
-s 4326 the SRID to record (the files are in EPSG:4326)
-a append to an existing table (-c would create one)
-F fill a column filename with each file’s name
-k keep rasters that are entirely nodata (by default they are skipped, and a day would go missing)
-e write plain statements without BEGIN and END, so that the transaction is yours

raster2pgsql can also add the index, the constraints and a VACUUM (-I, -C, -M); this chapter does those by hand, so that you see each one. The yearly files hold one band per day, and raster2pgsql makes one row per file, so each year goes in four steps, all in one transaction:

  1. Python writes each band to its own small GeoTIFF in a temporary folder, named after its day;
  2. raster2pgsql turns the folder into one INSERT per file, into a temporary table chirps_load;
  3. INSERT ... SELECT copies the rows into raw.chirps_rnl_daily, with the date taken from the file name;
  4. the transaction commits, and the temporary table disappears (ON COMMIT DROP).

A year is therefore either complete in the table or absent, and day is the table’s primary key from the start: a second raster for the same day is refused. The next cell defines the table and the loader, and loads 1981 only.

CHIRPS_DDL = """
CREATE TABLE IF NOT EXISTS raw.chirps_rnl_daily (
    day       date   PRIMARY KEY,
    rast      raster NOT NULL,
    filename  text   NOT NULL                -- chirps3_rnl_java_YYYYMMDD.tif
)"""
COPY_YEAR = """
INSERT INTO raw.chirps_rnl_daily (day, rast, filename)
SELECT to_date(substring(filename from '([0-9]{8})[.]tif$'), 'YYYYMMDD'), rast, filename
FROM chirps_load"""
proj = list((PG_BIN.parent / "share" / "contrib").glob("postgis-*/proj")) if PG_BIN else []
R2P_ENV = dict(os.environ) | ({"PROJ_DATA": str(proj[0]), "PROJ_LIB": str(proj[0])} if len(proj) == 1 else {})
# (PROJ data for raster2pgsql: without it, it warns that it cannot find proj.db; the SQL is the same, ledger L151)


def load_year(path: Path) -> int:
    """Load one yearly file into raw.chirps_rnl_daily in one transaction; return the number of days."""
    with tempfile.TemporaryDirectory() as tmp:
        with rasterio.open(path) as src:
            profile = src.profile | {"count": 1}
            for b in range(1, src.count + 1):
                day = src.descriptions[b - 1][1:]                  # band names are dYYYYMMDD
                with rasterio.open(Path(tmp) / f"chirps3_rnl_java_{day}.tif", "w", **profile) as dst:
                    dst.write(src.read(b), 1)
            n = src.count
        p = subprocess.run([RASTER2PGSQL, "-s", "4326", "-a", "-F", "-k", "-e", str(Path(tmp) / "*.tif"),
                            "chirps_load"], capture_output=True, env=R2P_ENV)
    if p.returncode:
        raise RuntimeError(p.stderr.decode(errors="replace")[-2000:])
    sql_text = p.stdout.decode()
    assert sql_text.count("INSERT INTO") == n, "raster2pgsql wrote fewer INSERTs than there are days"
    with connect() as conn:                                        # one transaction
        conn.execute("CREATE TEMP TABLE chirps_load (rast raster, filename text) ON COMMIT DROP")
        conn.execute(sql_text)
        copied = conn.execute(COPY_YEAR).rowcount
    assert copied == n
    return n


with connect() as conn:
    conn.execute(CHIRPS_DDL)
    loaded = {r[0] for r in conn.execute("SELECT DISTINCT extract(year FROM day)::int FROM raw.chirps_rnl_daily")}
if 1981 not in loaded:
    t = time.perf_counter()
    print("1981:", load_year(YEARLY / "chirps-v3.0-rnl-java-1981.tif"), f"days in {time.perf_counter() - t:.0f} s")
else:
    print("1981 already loaded")
1981: 365 days in 13 s

Look before moving on. One row, read back with three raster functions: ST_MetaData gives the grid (corner, size, cell size, SRID, number of bands), ST_BandMetaData the pixel type and nodata value of band 1, and ST_SummaryStats the count, mean and range of the cells that are not nodata. Right: 225 x 76 cells, SRID 4326, one band of 32BF with nodata -9999, 6,674 counted cells and no negative rainfall.

ONE_ROW = """
SELECT day, (m).upperleftx, (m).upperlefty, (m).width, (m).height, (m).scalex, (m).srid, (m).numbands,
       (b).pixeltype, (b).nodatavalue, (s).count, round((s).mean::numeric, 2) AS mean_mm,
       round((s).min::numeric, 2) AS min_mm, round((s).max::numeric, 2) AS max_mm
FROM (SELECT day, ST_MetaData(rast) AS m, ST_BandMetaData(rast, 1) AS b, ST_SummaryStats(rast) AS s
      FROM raw.chirps_rnl_daily WHERE day = '1981-01-01') r"""
with connect() as conn:
    row = conn.execute(ONE_ROW)
    print("\n".join(f"{d.name:12s} {v}" for d, v in zip(row.description, row.fetchone())))
day          1981-01-01
upperleftx   105.050004247576
upperlefty   -5.000000968575478
width        225
height       76
scalex       0.05000000074505806
srid         4326
numbands     1
pixeltype    32BF
nodatavalue  -9999.0
count        6674
mean_mm      24.02
min_mm       2.05
max_mm       87.56

Now the other 45 years, one transaction each, with a line per year. This is the long cell: about 12 seconds per year on the author’s computer, most of it writing the small files and running raster2pgsql (ledger L151).

with connect() as conn:
    loaded = {r[0] for r in conn.execute("SELECT DISTINCT extract(year FROM day)::int FROM raw.chirps_rnl_daily")}
t, this_run = time.perf_counter(), []
for path in sorted(YEARLY.glob("chirps-v3.0-rnl-java-*.tif")):
    year = int(path.stem[-4:])
    if year in loaded:
        continue
    n = load_year(path)
    this_run.append(year)
    print(f"{year}: {n} days | {time.perf_counter() - t:.0f} s", end="  ", flush=True)
    if len(this_run) % 4 == 0:
        print()
print(f"\nyears loaded in this run: {len(this_run)}; already there: {len(loaded)}")
1982: 365 days | 13 s  1983: 365 days | 26 s  1984: 366 days | 39 s  1985: 365 days | 51 s  
1986: 365 days | 64 s  1987: 365 days | 78 s  1988: 366 days | 90 s  1989: 365 days | 103 s  
1990: 365 days | 116 s  1991: 365 days | 129 s  1992: 366 days | 141 s  1993: 365 days | 153 s  
1994: 365 days | 166 s  1995: 365 days | 179 s  1996: 366 days | 192 s  1997: 365 days | 205 s  
1998: 365 days | 218 s  1999: 365 days | 230 s  2000: 366 days | 243 s  2001: 365 days | 256 s  
2002: 365 days | 269 s  2003: 365 days | 282 s  2004: 366 days | 294 s  2005: 365 days | 306 s  
2006: 365 days | 320 s  2007: 365 days | 332 s  2008: 366 days | 345 s  2009: 365 days | 359 s  
2010: 365 days | 371 s  2011: 365 days | 383 s  2012: 366 days | 396 s  2013: 365 days | 409 s  
2014: 365 days | 422 s  2015: 365 days | 435 s  2016: 366 days | 447 s  2017: 365 days | 460 s  
2018: 365 days | 473 s  2019: 365 days | 486 s  2020: 366 days | 498 s  2021: 365 days | 511 s  
2022: 365 days | 523 s  2023: 365 days | 536 s  2024: 366 days | 548 s  2025: 365 days | 561 s  
2026: 273 days | 570 s  
years loaded in this run: 45; already there: 1

Now the table’s finishing touches. A spatial index on rast would not help: every row covers the same window, so a bounding-box test could never rule a row out. The primary key on day is the index that matters.

Raster constraints are checks that PostGIS adds with AddRasterConstraints: in every row the same SRID, cell size, width and height, number of bands, pixel type and nodata value, the raster stored inside the database, an extent within the table’s maximum, and the same alignment, meaning that all grids line up cell for cell. Besides guarding the table, they fill the view raster_columns, which describes the table to other software. Call the function with named arguments (rastschema => ...): it has several versions, and with three plain text arguments PostgreSQL picks a version that reads them as table, column and list of constraints, without an error (ledger L152). It returns true even when it has to skip a constraint (it only warns, ledger L152), so the cell counts the constraints afterwards.

VACUUM ANALYZE reclaims space left over from loading and records statistics that PostgreSQL’s planner uses to choose how to run queries. It cannot run inside a transaction block (VACUUM), hence autocommit=True.

N_CONSTRAINTS = """SELECT count(*) FROM pg_constraint
                   WHERE conrelid = %s::regclass AND conname LIKE 'enforce%%rast'"""
with connect(autocommit=True) as conn:
    t = time.perf_counter()
    if conn.execute(N_CONSTRAINTS, ["raw.chirps_rnl_daily"]).fetchone()[0] == 0:
        conn.execute("SELECT AddRasterConstraints(rastschema => 'raw', rasttable => 'chirps_rnl_daily', "
                     "rastcolumn => 'rast')")
    n_constraints = conn.execute(N_CONSTRAINTS, ["raw.chirps_rnl_daily"]).fetchone()[0]
    conn.execute("COMMENT ON TABLE raw.chirps_rnl_daily IS 'CHIRPS v3.0 daily rnl, mm/day, Java window, "
                 "CC BY 4.0 (CHC, doi:10.15780/G2JQ0P); loaded by Chapter 4 from the yearly files (ledger L148)'")
    conn.execute("VACUUM ANALYZE raw.chirps_rnl_daily")
    cols = conn.execute("""SELECT srid, scale_x, scale_y, blocksize_x, blocksize_y, same_alignment,
                                  num_bands, pixel_types, nodata_values, ST_AsText(ST_Envelope(extent))
                           FROM raster_columns WHERE r_table_schema = 'raw' AND r_table_name = 'chirps_rnl_daily'""").fetchone()
    size = conn.execute("SELECT pg_size_pretty(pg_total_relation_size('raw.chirps_rnl_daily'))").fetchone()[0]
print(f"{n_constraints} raster constraints ({time.perf_counter() - t:.0f} s with VACUUM ANALYZE)")
for k, v in zip(["srid", "scale_x", "scale_y", "blocksize_x", "blocksize_y", "same_alignment", "num_bands",
                 "pixel_types", "nodata_values", "extent"], cols):
    print(f"{k:15s} {v}")
print("table size:", size)
11 raster constraints (10 s with VACUUM ANALYZE)
srid            4326
scale_x         0.0500000007
scale_y         -0.0500000007
blocksize_x     225
blocksize_y     76
same_alignment  True
num_bands       1
pixel_types     ['32BF']
nodata_values   [-9999.0]
extent          POLYGON((105.050004247576 -8.80000102519989,105.050004247576 -5.000000968575478,116.30000441521406 -5.000000968575478,116.30000441521406 -8.80000102519989,105.050004247576 -8.80000102519989))
table size: 473 MB

Look before moving on. SRID 4326; a cell size of 0.05 degree, negative in y because rows run from north to south; blocksize, the width and height of each row’s raster, 225 by 76; one band of 32BF with nodata -9999; same_alignment true; and an extent that is one window, since every row covers the same area.

5. Check the loaded table

Two checks. First, completeness: every day from the first to the last should have exactly one raster. The query makes the list of all dates in the record by adding 0, 1, 2, … days to the first one (generate_series(0, last - first), where subtracting two dates gives a number of days), and keeps the dates with no raster with an anti-join (LEFT JOIN ... WHERE r.day IS NULL).

COMPLETE = """
WITH span AS (SELECT min(day) AS first, max(day) AS last, count(*) AS n FROM raw.chirps_rnl_daily)
SELECT first, last, n,
       (SELECT count(*) FROM generate_series(0, last - first) AS g(i)
        LEFT JOIN raw.chirps_rnl_daily r ON r.day = first + g.i
        WHERE r.day IS NULL) AS missing_days
FROM span"""
with connect() as conn:
    print(dict(zip(["first_day", "last_day", "days_loaded", "missing_days"], conn.execute(COMPLETE).fetchone())))
{'first_day': datetime.date(1981, 1, 1), 'last_day': datetime.date(2026, 9, 30), 'days_loaded': 16709, 'missing_days': 0}

Second, values: the database and rasterio should read the same number from the same day and cell. ST_Value returns the value of the cell that contains a point. The point is the centre of the cell that contains 110 E, 7 S, in Kab. Batang (ledger L134); a cell centre, because a point on a cell’s edge would leave the answer to rounding. rasterio’s sample reads the same cell from the yearly file, independently of PostGIS. A value of 0 is a dry day; a missing raster would give no value at all.

POINT = (109.975, -6.975)                          # centre of the cell that contains 110 E, 7 S
DAYS = ["1981-01-01", "1998-02-14", "2019-01-15", "2024-02-29", "2026-09-30"]
with connect() as conn:
    db = dict(conn.execute("""SELECT day::text, ST_Value(rast, ST_SetSRID(ST_MakePoint(%s, %s), 4326))
                              FROM raw.chirps_rnl_daily WHERE day = ANY(%s::date[]) ORDER BY day""",
                           [*POINT, DAYS]).fetchall())
rows = []
for d in DAYS:
    day = dt.date.fromisoformat(d)
    with rasterio.open(YEARLY / f"chirps-v3.0-rnl-java-{day.year}.tif") as src:
        band = (day - dt.date(day.year, 1, 1)).days + 1
        file_value = float(next(src.sample([POINT], indexes=band))[0])
    rows.append((d, db[d], file_value))
pd.DataFrame(rows, columns=["day", "PostGIS mm", "rasterio mm"])
day PostGIS mm rasterio mm
0 1981-01-01 24.293768 24.293768
1 1998-02-14 4.687060 4.687060
2 2019-01-15 8.753820 8.753820
3 2024-02-29 3.451349 3.451349
4 2026-09-30 0.000000 0.000000

6. Dekads: adding rasters up in the database

A dekad is a third of a month: days 1 to 10, 11 to 20, and 21 to the end of the month, so 8 to 11 days. The index of this series works in dekads. CHC advises using pentad or longer totals rather than single days where possible (ledger L28), CHIRPS pentads end on the 5th, 10th, 15th, 20th, 25th and the last day of each month, so every dekad is exactly two pentads (ledger L153), and the crop calendar of Chapter 7 measures the stages of the rice crop in whole dekads.

ST_Union(rast, 'SUM') is an aggregate like sum, for rasters: with GROUP BY it adds up all rasters of a group cell by cell and returns one raster. It needs rasters on the same grid, which the constraint same_alignment guarantees. Nodata cells are left out of a sum (ledger L153); here every day has the same land cells, so a dekad has them too. The query assigns each day to the first day of its dekad with make_date, and HAVING keeps only complete dekads: the last dekad of the record would otherwise look dry because some of its days are missing (the length of a dekad that starts on the 21st is the first day of the next month minus its start).

ORDER BY day inside the aggregate fixes the order in which the days are added. PostGIS keeps the running total as a 32-bit float, whose last digits depend on the order of the additions; without it, the order is whatever order the rows are read in, and two builds of the same data differ by up to 0.00024 mm (ledger L149). With it, every build gives identical rasters. This takes about a minute.

CHIRPS_DEKAD = """
CREATE TABLE idx.chirps_dekad AS
WITH d AS (
    SELECT day, rast,
           make_date(extract(year FROM day)::int, extract(month FROM day)::int,
                     CASE WHEN extract(day FROM day) <= 10 THEN 1
                          WHEN extract(day FROM day) <= 20 THEN 11 ELSE 21 END) AS dekad_start
    FROM raw.chirps_rnl_daily
)
SELECT dekad_start, max(day) AS dekad_end, count(*)::int AS n_days, ST_Union(rast, 'SUM' ORDER BY day) AS rast
FROM d
GROUP BY dekad_start
HAVING count(*) = CASE WHEN extract(day FROM dekad_start) < 21 THEN 10
                       ELSE (date_trunc('month', dekad_start::timestamp) + interval '1 month')::date - dekad_start END"""

with connect() as conn:
    if conn.execute("SELECT to_regclass('idx.chirps_dekad')").fetchone()[0]:
        print("idx.chirps_dekad already exists: left as it is")
    else:
        t = time.perf_counter()
        conn.execute(CHIRPS_DEKAD)
        conn.execute("ALTER TABLE idx.chirps_dekad ADD PRIMARY KEY (dekad_start)")
        for col in ("dekad_end", "n_days", "rast"):
            conn.execute(f"ALTER TABLE idx.chirps_dekad ALTER COLUMN {col} SET NOT NULL")
        conn.execute("SELECT AddRasterConstraints(rastschema => 'idx', rasttable => 'chirps_dekad', rastcolumn => 'rast')")
        conn.execute("COMMENT ON TABLE idx.chirps_dekad IS 'Dekad rainfall (mm) from raw.chirps_rnl_daily: "
                     "ST_Union(rast, SUM ORDER BY day) over complete dekads, built by Chapter 4'")
        conn.execute("ANALYZE idx.chirps_dekad")
        print(f"idx.chirps_dekad built in {time.perf_counter() - t:.0f} s")
    print(dict(zip(["dekads", "first", "last", "min_days", "max_days"],
                   conn.execute("SELECT count(*), min(dekad_start), max(dekad_end), min(n_days), max(n_days) "
                                "FROM idx.chirps_dekad").fetchone())))
idx.chirps_dekad built in 60 s
{'dekads': 1647, 'first': datetime.date(1981, 1, 1), 'last': datetime.date(2026, 9, 30), 'min_days': 8, 'max_days': 11}

Look before moving on. Check one sum outside the database. The cell takes two dekads, one ending in a leap day, adds up the right bands of the yearly file with numpy, and compares every land cell with the dekad raster, which it reads back from PostGIS as a GeoTIFF (ST_AsGDALRaster, Chapter 2). It also checks that the sea came back as nodata. A difference of whole millimetres would mean a day missing or counted twice; the rounding of 32-bit floats stays far below 0.001 mm.

def dekad_from_db(start: str) -> np.ndarray:
    with connect() as conn:
        tif = conn.execute("SELECT ST_AsGDALRaster(rast, 'GTiff') FROM idx.chirps_dekad WHERE dekad_start = %s",
                           [start]).fetchone()[0]
    with MemoryFile(bytes(tif)) as mem, mem.open() as src:
        return src.read(1)


for start in ["2019-08-01", "2024-02-21"]:
    first = dt.date.fromisoformat(start)
    with connect() as conn:
        last = conn.execute("SELECT dekad_end FROM idx.chirps_dekad WHERE dekad_start = %s", [start]).fetchone()[0]
    with rasterio.open(YEARLY / f"chirps-v3.0-rnl-java-{first.year}.tif") as src:
        bands = range((first - dt.date(first.year, 1, 1)).days + 1, (last - dt.date(first.year, 1, 1)).days + 2)
        stack = src.read(list(bands))
    land = (stack != -9999).all(axis=0)
    by_numpy = stack.sum(axis=0, dtype="float64")
    by_postgis = dekad_from_db(start)
    diff = np.abs(by_postgis[land] - by_numpy[land]).max()
    assert diff < 1e-3 and (by_postgis[~land] == -9999).all()
    print(f"{start} to {last} ({len(bands)} days): largest difference over {int(land.sum())} land cells "
          f"{diff:.6f} mm; sea cells nodata")
2019-08-01 to 2019-08-10 (10 days): largest difference over 6674 land cells 0.000008 mm; sea cells nodata
2024-02-21 to 2024-02-29 (9 days): largest difference over 6674 land cells 0.000027 mm; sea cells nodata

Now a map of two dekads of 2019, one in the wet season and one in the dry season, with the province borders of Chapter 3 on top. Sea cells are nodata and stay blank. The colour scale stops at 250 mm so that the wet dekad does not wash out; the title gives the mean over all land cells of the window.

provinces = gpd.read_postgis("SELECT name, ST_SimplifyPreserveTopology(geometry, 0.01) AS geometry FROM ref.province",
                             ENGINE, geom_col="geometry")
fig, axes = plt.subplots(2, 1, figsize=(10, 6.2))
for ax, start in zip(axes, ["2019-01-21", "2019-08-11"]):
    with connect() as conn:
        tif, end = conn.execute("SELECT ST_AsGDALRaster(rast, 'GTiff'), dekad_end FROM idx.chirps_dekad "
                                "WHERE dekad_start = %s", [start]).fetchone()
    with MemoryFile(bytes(tif)) as mem, mem.open() as src:
        grid, b = src.read(1, masked=True), src.bounds
    im = ax.imshow(grid, extent=(b.left, b.right, b.bottom, b.top), cmap="YlGnBu", vmin=0, vmax=250)
    provinces.boundary.plot(ax=ax, color="0.3", linewidth=0.5)
    ax.set_title(f"{start} to {end}: window mean {grid.mean():.0f} mm")
    ax.set_axis_off()
fig.colorbar(im, ax=axes, shrink=0.7, label="rainfall in the dekad (mm)")
plt.show()

Two maps of the Java window, dekad rainfall in millimetres, 21-31 January 2019 with heavy rain over most of the island, and 11-20 August 2019 with little rain.

7. What is final, and what may change

CHIRPS is not fixed once published. CHC produces the final product once a month, typically in the third week of the following month (ledger L27), and it can publish a revised release of months already out: in November 2026 it re-released the daily data for October 2025 to September 2026, and every one of those 365 days changed, some cells by more than 80 mm (ledger L36). The yearly files of this series hold the re-released values (ledger L148), but a later release could change the recent months again. Results built on them can move: the re-release changed the payout status of 4 units in the MK1 season and 1 in the MH season of crop year 2025 (ledger L98; the seasons and payouts come in Chapters 7 and 9).

So the series records, per source, the first day, the last day available and the last day it treats as final, in a small table, idx.data_status. Later chapters read it to mark results that rest on data after final_through as provisional, and nothing else has to be rebuilt when the dates move.

  • CHIRPS: available through the last day loaded; final through 30 September 2025, the day before the period CHC re-released.
  • Damage reports (Chapter 3): the pages printed the update date 27 November 2026. Data are available through the end of that month, 30 November 2026, a month that is itself partial; only years before the year of the update date are treated as final, so final through 31 December 2025. (A request for older years once printed an earlier update date, 7 September 2026, so the ministry was still editing older years in 2026, ledger L2.)

ON CONFLICT (source) DO NOTHING keeps a row that is already there: once written, the table is edited by hand when a source changes, and rerunning the chapter does not overwrite it. The CHIRPS row first.

DATA_STATUS_DDL = """
CREATE TABLE IF NOT EXISTS idx.data_status (
    source             text PRIMARY KEY,
    first_day          date NOT NULL,
    available_through  date NOT NULL,
    final_through      date NOT NULL CHECK (final_through <= available_through),
    note               text
)"""
CHIRPS_STATUS = """
INSERT INTO idx.data_status (source, first_day, available_through, final_through, note)
SELECT 'chirps_rnl', min(day), max(day), DATE '2025-09-30',
       'CHIRPS v3 rnl daily in raw.chirps_rnl_daily. CHC re-released 2025-10-01..2026-09-30 in November 2026 '
       '(ledger L36): treat days after 2025-09-30 as provisional until a later release leaves them unchanged.'
FROM raw.chirps_rnl_daily
ON CONFLICT (source) DO NOTHING"""
with connect() as conn:
    conn.execute(DATA_STATUS_DDL)
    conn.execute(CHIRPS_STATUS)

Then the damage reports. The update date is read in Python from the text the pages print, with Indonesian month names, as in Chapter 3, and passed to the query as a parameter (%(updated)s).

MONTHS = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September",
          "Oktober", "November", "Desember"]
DAMAGE_STATUS = """
WITH u AS (SELECT %(updated)s::date AS updated)
INSERT INTO idx.data_status (source, first_day, available_through, final_through, note)
SELECT 'datanonkom_dpi',
       (SELECT make_date(min(year), 1, 1) FROM raw.datanonkom_damage
        WHERE topik = 3 AND ha IS NOT NULL),                    -- topik 3: DPI, flood and drought (Chapter 3)
       (date_trunc('month', u.updated::timestamp) + interval '1 month' - interval '1 day')::date,
       make_date(extract(year FROM u.updated)::int - 1, 12, 31),
       'datanonkom DPI (flood, drought) monthly damage, Chapter 3. 0.00 also means not reported yet: '
       'the year of the update date is provisional.'
FROM u
ON CONFLICT (source) DO NOTHING"""

with connect() as conn:
    printed = [r[0] for r in conn.execute("SELECT DISTINCT source_update FROM raw.datanonkom_damage")]
    assert len(printed) == 1, f"the pages printed different update dates: {printed}"
    d, month, y = printed[0].split()                  # e.g. '27 November 2026', in Indonesian
    updated = dt.date(int(y), MONTHS.index(month) + 1, int(d))
    print("damage pages updated", updated)
    conn.execute(DAMAGE_STATUS, {"updated": updated})
    status = pd.DataFrame(conn.execute("SELECT source, first_day, available_through, final_through "
                                       "FROM idx.data_status ORDER BY source").fetchall(),
                          columns=["source", "first_day", "available_through", "final_through"])
status
damage pages updated 2026-11-27
source first_day available_through final_through
0 chirps_rnl 1981-01-01 2026-09-30 2025-09-30
1 datanonkom_dpi 2016-01-01 2026-11-30 2025-12-31

Look before moving on. The two rows should read as the list above says: CHIRPS from 1 January 1981, available through 30 September 2026, final through 30 September 2025; damage reports from 2016, available through 30 November 2026, final through 31 December 2025.

When CHC publishes a newer release, the steps are:

  1. get the changed years as yearly files, with a new checksum list (the series publishes them as a new release; scripts/fetch_chirps_cog.py in the repository reads changed days from CHC’s COGs);
  2. compare them with the files you have, for example with the check of section 3;
  3. delete those years and the dekads, then run sections 4 to 6 again: DELETE FROM raw.chirps_rnl_daily WHERE extract(year FROM day) IN (2025, 2026) and DROP TABLE idx.chirps_dekad (and the tables that later chapters build on it);
  4. update idx.data_status by hand, for example UPDATE idx.data_status SET final_through = DATE '2026-06-30' WHERE source = 'chirps_rnl'.

Checkpoint

The cell below checks, in a new session, what the next chapters rely on: one raster per day with no gaps, on one grid; a dekad raster for exactly every complete dekad of the daily record, with the right number of days and no negative rain (so a dekad table left over from an older daily record is caught); and status rows that match the loaded data. It depends only on the setup cell.

EXPECTED_DEKADS = """
SELECT dekad_start, count(*)::int AS n_days
FROM (SELECT make_date(extract(year FROM day)::int, extract(month FROM day)::int,
                     CASE WHEN extract(day FROM day) <= 10 THEN 1
                          WHEN extract(day FROM day) <= 20 THEN 11 ELSE 21 END) AS dekad_start
      FROM raw.chirps_rnl_daily) d
GROUP BY dekad_start
HAVING count(*) = CASE WHEN extract(day FROM dekad_start) < 21 THEN 10
                       ELSE (date_trunc('month', dekad_start::timestamp) + interval '1 month')::date - dekad_start END"""

with connect() as conn:
    first_row = lambda q: conn.execute(q).fetchone()
    n_days, first, last = first_row("SELECT count(*), min(day), max(day) FROM raw.chirps_rnl_daily")
    daily = first_row("""SELECT srid, same_alignment, num_bands, pixel_types FROM raster_columns
                         WHERE r_table_schema = 'raw' AND r_table_name = 'chirps_rnl_daily'""")
    dekad = first_row("""SELECT srid, same_alignment, num_bands, pixel_types FROM raster_columns
                         WHERE r_table_schema = 'idx' AND r_table_name = 'chirps_dekad'""")
    mismatch = first_row(f"""SELECT (SELECT count(*) FROM (({EXPECTED_DEKADS}) EXCEPT
                                         SELECT dekad_start, n_days FROM idx.chirps_dekad) a),
                                    (SELECT count(*) FROM (SELECT dekad_start, n_days FROM idx.chirps_dekad EXCEPT
                                         ({EXPECTED_DEKADS})) b)""")
    n_dek, min_mm, max_mm = first_row("SELECT count(*), min((ST_SummaryStats(rast)).min), "
                                      "max((ST_SummaryStats(rast)).max) FROM idx.chirps_dekad")
    status = {r[0]: r[1:] for r in conn.execute("SELECT source, first_day, available_through, final_through "
                                                "FROM idx.data_status")}

assert n_days == (last - first).days + 1 and first == dt.date(1981, 1, 1), f"{n_days} rasters for {first} to {last}"
assert daily == (4326, True, 1, ["32BF"]) and dekad == (4326, True, 1, ["32BF"]), f"constraints: {daily}, {dekad}"
assert mismatch == (0, 0), f"dekads missing / unexpected: {mismatch}"
assert min_mm >= 0, f"negative dekad rainfall: {min_mm}"
assert status["chirps_rnl"] == (first, last, dt.date(2025, 9, 30)), f"chirps_rnl status: {status['chirps_rnl']}"
assert status["datanonkom_dpi"][2] == dt.date(2025, 12, 31), f"datanonkom_dpi status: {status['datanonkom_dpi']}"
print(f"checkpoint passed: {n_days:,} days {first} to {last}, {n_dek:,} dekads (0 to {max_mm:.0f} mm), "
      f"status rows {sorted(status)}; code cells took {time.perf_counter() - T0:.0f} s since the setup cell")
checkpoint passed: 16,709 days 1981-01-01 to 2026-09-30, 1,647 dekads (0 to 1314 mm), status rows ['chirps_rnl', 'datanonkom_dpi']; code cells took 666 s since the setup cell

Troubleshooting

Symptom Cause Fix
relation "ref.province" does not exist or relation "raw.datanonkom_damage" does not exist Chapter 3 has not been run run Chapter 3 first
raster2pgsql not found pg_bin in config.yml does not point to PostgreSQL’s bin folder set it to the folder that holds raster2pgsql.exe (Windows) or to null if it is on your PATH
404 when downloading a yearly file the files are not at the URL in config.yml check chirps.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/chirps/java_yearly and run the cell again
the CHC check fails with an HTTP error (403, 404, timeout) no internet, CHC’s server is busy, or it refuses the request run the cell again later; the rest of the chapter does not depend on it
loading stopped in the middle the cell was interrupted run it again: each year is one transaction, so a year is either complete or absent, and finished years are skipped
duplicate key value violates unique constraint "chirps_rnl_daily_pkey" a year that is already in the table was loaded again delete it first: DELETE FROM raw.chirps_rnl_daily WHERE extract(year FROM day) = 2019
same_alignment is false in raster_columns, or fewer constraints than expected a raster on another grid got into the table (AddRasterConstraints only warns, ledger L152) find it with SELECT day FROM raw.chirps_rnl_daily WHERE NOT ST_SameAlignment(rast, (SELECT rast FROM raw.chirps_rnl_daily WHERE day = '1981-01-01')), delete it and load its year again
idx.chirps_dekad already exists, but the daily data changed the cell does not rebuild an existing table DROP TABLE idx.chirps_dekad in a new cell (and the tables later chapters built on it), then run section 6 again

Summary

You now have:

  • raw.chirps_rnl_daily: one raster per day, 1 January 1981 to 30 September 2026, mm per day, with day as primary key and raster constraints;
  • idx.chirps_dekad: one raster per complete dekad, the sum of its days, which Chapter 6 turns into rainfall per insured unit;
  • idx.data_status: per source, the first day, the last day available and the last day treated as final, which later chapters use to mark provisional results;
  • in data_dir: the 46 yearly files (about 385 MB) and one day read from CHC for the check.

What comes next

Chapter 5 loads the paddy fields of Java and chooses the insured units: the kabupaten/kota with enough rice to insure.

References