Skip to main content

Chapter 12: Serving payouts as a web map

Chapter 12: Serving payouts as a web map

TipAt a glance
  • You will build: the functions out.payout_tile_features and out.payout_tile (vector tiles of payouts straight from the database), a small local tile server and a MapLibre web map in data_dir/webmap
  • You need: Chapter 9; a web browser with internet access to open the live map
  • Time to run: Under a minute (the checkpoint prints the time)
  • Level: Intermediate

The last step of the series takes the results out of the notebook. A web map can show every insured unit’s payout for any season and crop year, and it can do so straight from the database: PostGIS cuts the map into vector tiles, small packages of geometry and attributes for one square of the map at one zoom level, in the Mapbox Vector Tile (MVT) format, and a web server hands them to a map in the browser. Nothing is exported in between, so the map shows what the tables hold at the moment it is drawn. This chapter writes the tile function in SQL, serves it with a few lines of Python, shows inside the notebook what the server sends, and draws the live map with MapLibre GL JS, a map library for the browser. Payouts remain illustrative.

NoteLearning objectives

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

  • explain web map tiles: Web Mercator (EPSG:3857) and the z/x/y numbering;
  • cut a vector tile in SQL with ST_TileEnvelope, ST_AsMVTGeom and ST_AsMVT;
  • write a tile function with the signature the tile server pg_tileserv looks for, and check what a tile holds without decoding it;
  • serve tiles from Python’s standard library and draw them on a MapLibre map;
  • say what a published, static website can and cannot show of a database.

Before running this chapter:

  • complete Chapter 9, which builds out.payout and idx.contract, and the chapters before it;
  • to look at the live map, have a web browser with internet access: the map page loads MapLibre from a CDN, a public server that hosts web libraries;
  • allow under a minute. The notebook downloads nothing. The functions are replaced on every run, and the server is started and stopped inside the cells that use it.

1. Setup

The setup cell reads config.yml, defines connect() and ENGINE as in the earlier chapters, and checks the tables of the earlier chapters. Its settings:

  • SEASON and YEAR, the season and crop year the map opens with: the MK1 of crop year 2018, which grew in the dry season of 2019, one of the crop years in which many units paid (Chapter 9, section 5);
  • PORT, the port of the local web server: the number that routes a request on this computer to one program. 8799 is seldom used by other programs; the server listens on 127.0.0.1, this computer only;
  • WEBMAP, the folder in data_dir where the map page is written.

It also reads the range of crop years in out.payout, which the server accepts.

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

import datetime as dt
import math
import struct
import threading
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import psycopg
import yaml
from matplotlib.patches import PathPatch
from matplotlib.path import Path as DrawPath
from sqlalchemy import URL, create_engine

T0 = time.perf_counter()
SEASON, YEAR = "MK1", 2018          # what the map opens with
PORT = 8799                         # local web server, 127.0.0.1 only

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"]
WEBMAP = Path(CONFIG["data_dir"]) / "webmap"


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.insured_unit", "idx.contract", "idx.data_status", "out.payout"]:
        if not conn.execute("SELECT to_regclass(%s)", [table]).fetchone()[0]:
            raise RuntimeError(f"{table} is missing: run Chapters 3 to 9 first")
    FIRST_YEAR, LAST_YEAR = conn.execute("SELECT min(crop_year), max(crop_year) FROM out.payout").fetchone()
WEBMAP.mkdir(parents=True, exist_ok=True)
print(f"map opens with {SEASON} {YEAR}; crop years {FIRST_YEAR}-{LAST_YEAR}; server on http://127.0.0.1:{PORT}/; "
      f"page written to {WEBMAP}")
connected | POSTGIS="3.7.0 3.7.0" [EXTENSION] PGSQL="180" GEOS="3.15.1-C ...
map opens with MK1 2018; crop years 1981-2025; server on http://127.0.0.1:8799/; page written to E:\temp\pgci\webmap

2. Tiles: squares of the map at each zoom level

Web maps are drawn from tiles. They use the Web Mercator projection (EPSG:3857), which turns the world, up to about 85 degrees north and south, into a square that can be cut into equal parts; areas grow towards the poles, but almost every web map uses it. At zoom level z the square is a grid of 2^z by 2^z tiles, numbered by column x from the west and row y from the north; each zoom level doubles the grid in both directions. A map in the browser asks only for the tiles it shows, at the zoom it shows them, so a map of all of Java needs a few tiles at a low zoom and a close-up of one kabupaten a few tiles at a high zoom.

ST_TileEnvelope(z, x, y) returns the square of a tile as a polygon in EPSG:3857. The Python function below gives the tile that holds a longitude and latitude, by the formula of the OpenStreetMap tile scheme (see the references); the cell lists how many tiles cover Java’s bounding box at a few zoom levels.

def tile_of(lon: float, lat: float, z: int) -> tuple[int, int]:
    """Column x and row y of the Web Mercator tile at zoom z that holds a point."""
    n = 2 ** z
    x = int((lon + 180) / 360 * n)
    y = int((1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n)
    return x, y


with connect() as conn:
    west, south, east, north = conn.execute(
        "SELECT ST_XMin(e), ST_YMin(e), ST_XMax(e), ST_YMax(e) FROM (SELECT ST_Extent(geometry) AS e FROM ref.kabupaten) s"
    ).fetchone()


def java_tiles(z: int) -> list[tuple[int, int, int]]:
    """Every tile at zoom z that meets the bounding box of the boundaries."""
    x0, y0 = tile_of(west, north, z)
    x1, y1 = tile_of(east, south, z)
    return [(z, x, y) for x in range(x0, x1 + 1) for y in range(y0, y1 + 1)]


CENTRAL = (6, *tile_of(110.4, -7.3, 6))             # the zoom-6 tile over central Java, used below
print(f"bounding box of the boundaries: {west:.2f} to {east:.2f} degrees east, {-north:.2f} to {-south:.2f} degrees south")
for z in (5, 6, 8, 10):
    print(f"zoom {z:2d}: {len(java_tiles(z)):4d} tiles")
with connect() as conn:
    env = conn.execute("SELECT ST_AsText(ST_TileEnvelope(%s, %s, %s)), ST_SRID(ST_TileEnvelope(%s, %s, %s))",
                       [*CENTRAL, *CENTRAL]).fetchone()
print(f"tile {'/'.join(map(str, CENTRAL))}: {env[0][:70]}... SRID {env[1]}")
bounding box of the boundaries: 105.10 to 116.27 degrees east, 5.04 to 8.78 degrees south
zoom  5:    2 tiles
zoom  6:    6 tiles
zoom  8:   36 tiles
zoom 10:  396 tiles
tile 6/51/33: POLYGON((11897270.578531113 -1252344.271424327,11897270.578531113 -626... SRID 3857

Look before moving on. The bounding box reaches beyond Java’s main island, to its small islands in the Java Sea and east of Madura. At low zoom Java fits in a few tiles; once tiles are much smaller than Java, the count grows by close to four with each zoom level (from zoom 8 to 10 here). The envelope should be in metres (SRID 3857), not degrees.

3. One tile, by hand

A vector tile holds geometry in the tile’s own coordinates, a grid of 4,096 by 4,096 units by default (the tile’s extent, not to be confused with ST_Extent above), plus the attributes of each feature. Three functions make one:

  • ST_Transform(geometry, 3857) moves the boundaries from longitude and latitude into Web Mercator;
  • ST_AsMVTGeom(geom, envelope, 4096, 64, true) converts a geometry to tile coordinates and clips it (true) to the tile plus a buffer of 64 units, so that outlines show no seams at tile edges;
  • ST_AsMVT(rows, 'units') packs all rows into one tile, as a layer called units, and returns it as bytea, PostgreSQL’s type for raw bytes.

The rows are picked with k.geometry && envelope, the tile’s envelope moved back to longitude and latitude and widened by the same buffer, margin => 64.0 / 4096 (an argument passed by name). The test compares bounding boxes, which a GiST index can answer for large tables; with 119 boundaries PostgreSQL may also simply read them all.

The boundaries are simplified first with ST_Simplify, to about one unit of the tile’s grid at that zoom, finer than a screen shows: the width of the Web Mercator square, 40,075,016.69 m (2 pi times the 6,378,137 m radius of the sphere EPSG:3857 uses), divided by 2^z and by 4,096. The third argument of ST_Simplify, true, keeps small units that simplification would otherwise remove. The cell builds the tile over central Java with and without simplification, each twice, and keeps the second time, so that both run with the data already in memory.

ONE_TILE = """
WITH b AS (SELECT ST_TileEnvelope(%(z)s, %(x)s, %(y)s) AS env,
                  ST_Transform(ST_TileEnvelope(%(z)s, %(x)s, %(y)s, margin => 64.0 / 4096), 4326) AS env_lonlat,
                  2 * pi() * 6378137 / 2 ^ %(z)s / 4096 AS px)
SELECT length(ST_AsMVT(t, 'units')) AS bytes, count(*) AS features
FROM (SELECT k.code, k.name,
             ST_AsMVTGeom(CASE WHEN %(simplify)s THEN ST_Simplify(ST_Transform(k.geometry, 3857), b.px, true)
                               ELSE ST_Transform(k.geometry, 3857) END,
                          b.env, 4096, 64, true) AS geom
      FROM ref.kabupaten k CROSS JOIN b
      WHERE k.geometry && b.env_lonlat) t
WHERE t.geom IS NOT NULL"""
z, x, y = CENTRAL
with connect() as conn:
    for simplify in (False, True):
        for attempt in (1, 2):
            t = time.perf_counter()
            nbytes, features = conn.execute(ONE_TILE, {"z": z, "x": x, "y": y, "simplify": simplify}).fetchone()
            seconds = time.perf_counter() - t
        print(f"tile {z}/{x}/{y}, simplified {simplify!s:5s}: {features} features, {nbytes:,} bytes, {seconds:.2f} s")
tile 6/51/33, simplified False: 98 features, 176,887 bytes, 1.39 s
tile 6/51/33, simplified True : 98 features, 46,834 bytes, 0.82 s

Look before moving on. Both tiles should hold the same features; the simplified one should be much smaller and quicker to cut. A browser loads several tiles for every view, so their size and the time to cut them decide how fast the map feels.

4. A tile function

A tile server needs one thing from the database: given z, x and y, the bytes of the tile. That is a function. It is written in two parts, so that a tile’s content can be inspected without decoding its bytes:

  • out.payout_tile_features(z, x, y, crop_year, season) returns the rows of the tile, one per kabupaten/kota, with its payout for the season, the index, trigger and exit (Chapter 9), whether the season is provisional (Chapter 10), and the clipped geometry. It is declared RETURNS TABLE (...), a function queried like a table in FROM. A LEFT JOIN keeps the kabupaten/kota that are not insured, drawn in grey;
  • out.payout_tile(z, x, y, crop_year, season) packs those rows into one tile: ST_AsMVT(f, ...) takes each whole row f and makes its columns the feature’s attributes; rows without geometry are left out by ST_AsMVT itself.

The bodies are written between $$ signs (dollar quoting, as in Chapter 10), since they hold several lines of SQL. Both functions read tables, so they are STABLE: the same arguments give the same result within one query, but not across changes to the tables (Chapter 9 explained IMMUTABLE, which would be wrong here). The parameters crop_year and season have the same names as columns, so inside the body they are written with the function’s name, payout_tile_features.season; in a SQL function an unqualified name means the column.

The signature, three integers z, x and y first and bytea returned, is the one pg_tileserv looks for in function layers; the function should be servable by it (not tested here), though its built-in preview expects a layer named default, not units. CREATE OR REPLACE cannot change the columns a function returns, so the cell drops both functions first.

TILE_FUNCTIONS = [
    "DROP FUNCTION IF EXISTS out.payout_tile(integer, integer, integer, integer, text)",
    "DROP FUNCTION IF EXISTS out.payout_tile_features(integer, integer, integer, integer, text)",
    """
CREATE FUNCTION out.payout_tile_features(z integer, x integer, y integer,
                                         crop_year integer DEFAULT 2018, season text DEFAULT 'MK1')
RETURNS TABLE (code text, name text, insured boolean, season_label text, index_value double precision,
               trigger_value double precision, exit_value double precision, payout_frac double precision,
               provisional boolean, geom geometry)
LANGUAGE sql STABLE PARALLEL SAFE AS $$
    WITH b AS (SELECT ST_TileEnvelope(z, x, y) AS env,
                      ST_Transform(ST_TileEnvelope(z, x, y, margin => 64.0 / 4096), 4326) AS env_lonlat,
                      2 * pi() * 6378137 / 2 ^ z / 4096 AS px)
    SELECT k.code::text, k.name, u.code IS NOT NULL, p.season_label, p.index_value, c.trigger_value, c.exit_value,
           p.payout_frac, p.season_end > d.final_through,
           ST_AsMVTGeom(ST_Simplify(ST_Transform(k.geometry, 3857), b.px, true), b.env, 4096, 64, true)
    FROM ref.kabupaten k
    CROSS JOIN b
    LEFT JOIN idx.insured_unit u ON u.code = k.code
    LEFT JOIN out.payout p ON p.kabupaten_code = k.code AND p.season = payout_tile_features.season
                          AND p.crop_year = payout_tile_features.crop_year
    LEFT JOIN idx.contract c ON c.kabupaten_code = k.code AND c.season = payout_tile_features.season
    LEFT JOIN idx.data_status d ON d.source = 'chirps_rnl'
    WHERE k.geometry && b.env_lonlat
$$""", """
CREATE FUNCTION out.payout_tile(z integer, x integer, y integer,
                                crop_year integer DEFAULT 2018, season text DEFAULT 'MK1')
RETURNS bytea
LANGUAGE sql STABLE PARALLEL SAFE AS $$
    SELECT ST_AsMVT(f, 'units', 4096, 'geom')
    FROM out.payout_tile_features(z, x, y, crop_year, season) AS f
$$"""]

with connect() as conn:
    for statement in TILE_FUNCTIONS:
        conn.execute(statement)
    conn.execute("COMMENT ON FUNCTION out.payout_tile(integer, integer, integer, integer, text) IS 'Vector tile (MVT, "
                 "layer units) of payouts per kabupaten/kota for one season and crop year; illustrative; Chapter 12'")
rows = pd.read_sql("""SELECT code, name, insured, season_label, round(index_value::numeric, 3) AS index_value,
                             round(payout_frac::numeric, 3) AS payout_frac, provisional, geom IS NOT NULL AS has_geom
                      FROM out.payout_tile_features(%(z)s, %(x)s, %(y)s, %(year)s, %(season)s)
                      ORDER BY insured, payout_frac DESC NULLS LAST""", ENGINE,
                   params={"z": z, "x": x, "y": y, "year": YEAR, "season": SEASON})
with connect() as conn:                                # read after the block above has committed the functions
    nbytes = conn.execute("SELECT length(out.payout_tile(%s, %s, %s, %s, %s))", [z, x, y, YEAR, SEASON]).fetchone()[0]
print(f"tile {z}/{x}/{y}, {SEASON} {YEAR}: {len(rows)} rows, {int(rows.has_geom.sum())} with geometry, {nbytes:,} bytes; "
      f"insured {int(rows.insured.sum())}, not insured {int((~rows.insured).sum())}")
pd.concat([rows[~rows.insured].head(2), rows[rows.insured].head(6)])
tile 6/51/33, MK1 2018: 98 rows, 98 with geometry, 49,705 bytes; insured 79, not insured 19
code name insured season_label index_value payout_frac provisional has_geom
0 3576 Kota Mojokerto False NaN NaN NaN None True
1 3271 Kota Bogor False NaN NaN NaN None True
19 3203 Cianjur True MK1 2018/19 0.800 1.0 False True
20 3216 Bekasi True MK1 2018/19 0.867 1.0 False True
21 3327 Pemalang True MK1 2018/19 0.811 1.0 False True
22 3501 Pacitan True MK1 2018/19 0.844 1.0 False True
23 3329 Brebes True MK1 2018/19 0.822 1.0 False True
24 3205 Garut True MK1 2018/19 0.767 1.0 False True

Look before moving on. The rows are what the map will show in that square: insured units with a season label and a payout, the others with insured false and no payout. A row whose bounding box meets the tile but whose outline reaches neither the tile nor its buffer comes back without geometry (has_geom false) and is left out of the tile. The tile is a little larger than the one of section 3 because each feature now carries more attributes.

5. Serving the tiles

A browser fetches tiles over HTTP, at addresses such as /tiles/6/51/33.pbf (.pbf, protocol-buffer file, the binary format of vector tiles; section 6). Python’s standard library has what a local server needs: ThreadingHTTPServer answers several requests at once, each in its own thread, and a small handler class decides what each address returns:

  • /tiles/{z}/{x}/{y}.pbf?year=...&season=...: the bytes of out.payout_tile, with the content type of vector tiles, which tells the browser what the bytes are. z, x, y and the year are converted to integers and checked against their ranges, and the season against its two values, before they reach the database, and they are passed as query parameters, never pasted into the SQL. Anything wrong gives an error status (400 for a bad request, 500 for a failure of the server) instead of a broken connection;
  • /: the map page written below.

The server listens on 127.0.0.1, so only this computer can reach it, and runs in a background thread, so the notebook keeps working; start_server() and stop_server() start and stop it. On Windows the class TileServer turns off address reuse: with it on, as in Python’s own HTTPServer, a second server could bind a port another server already holds and never hear its requests (ledger L173). This is a teaching server: one database connection per tile and no cache.

class TileHandler(BaseHTTPRequestHandler):
    """Answer /tiles/z/x/y.pbf with a vector tile from the database, and / with the map page."""

    def do_GET(self):
        url = urlparse(self.path)
        parts = url.path.strip("/").split("/")
        try:
            if url.path == "/":
                body, kind = (WEBMAP / "index.html").read_bytes(), "text/html; charset=utf-8"
            elif len(parts) == 4 and parts[0] == "tiles" and parts[3].endswith(".pbf"):
                z, x, y = int(parts[1]), int(parts[2]), int(parts[3][:-4])
                query = parse_qs(url.query)
                year = int(query.get("year", [YEAR])[0])
                season = query.get("season", [SEASON])[0]
                if not (0 <= z <= 14 and 0 <= x < 2 ** z and 0 <= y < 2 ** z and FIRST_YEAR <= year <= LAST_YEAR
                        and season in ("MH", "MK1")):
                    raise ValueError("tile or setting out of range")
                with connect() as conn:
                    body = conn.execute("SELECT out.payout_tile(%s, %s, %s, %s, %s)", [z, x, y, year, season]).fetchone()[0]
                kind = "application/vnd.mapbox-vector-tile"
            else:
                self.send_error(404)
                return
        except ValueError:
            self.send_error(400, "bad request: tile or setting out of range")
            return
        except Exception as error:                     # database or file errors: report, do not drop the connection
            print(f"tile server error on {self.path}: {type(error).__name__}: {error}")
            self.send_error(500, "server error, see the notebook output")
            return
        self.send_response(200)
        self.send_header("Content-Type", kind)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):          # keep the notebook quiet
        pass


class TileServer(ThreadingHTTPServer):
    # On Windows, address reuse lets a second server bind a port another reusing server holds (ledger L173); on Linux
    # and macOS it is needed to restart on the same port soon after a stop, so it stays on there.
    allow_reuse_address = os.name != "nt"


if "SERVER" not in globals():              # running this cell again must not lose track of a running server
    SERVER = {"server": None}


def start_server():
    """Start the tile server in a background thread."""
    if SERVER["server"] is None:
        SERVER["server"] = TileServer(("127.0.0.1", PORT), TileHandler)
        threading.Thread(target=SERVER["server"].serve_forever, daemon=True).start()
    print(f"serving on http://127.0.0.1:{PORT}/")


def stop_server():
    """Stop the tile server and free the port."""
    if SERVER["server"] is not None:
        SERVER["server"].shutdown()
        SERVER["server"].server_close()
        SERVER["server"] = None
    print("server stopped")


FETCH = urllib.request.build_opener(urllib.request.ProxyHandler({}))   # never send 127.0.0.1 through a proxy

The map page is a short HTML file. It loads MapLibre GL JS from the unpkg CDN at a fixed version, 4.7.1, so the page does not change when MapLibre does. It defines one vector source whose tile address points at this server, and one fill layer that colours each unit by its payout share; the colour is a MapLibre expression (see the references): grey where the unit is not insured, light blue where it is insured but has no payout record for that crop year, otherwise a scale from 0 to 1. A season list and a year field change the tile address, a legend explains the colours, and a click opens a popup with the index, trigger, exit and payout. The page credits the rainfall and boundary data and says that payouts are illustrative. The cell writes it to WEBMAP.

VIEWER = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Payouts by insured unit</title>
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css">
<script src="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js"></script>
<style>
  body { margin: 0; font: 14px sans-serif; }
  #bar { padding: 6px 12px; background: #ffffff; border-bottom: 1px solid #cccccc; line-height: 1.8; }
  #map { position: absolute; top: 72px; bottom: 0; width: 100%; }
  .key { display: inline-block; width: 14px; height: 14px; vertical-align: middle; margin: 0 2px 0 8px; }
  #note { color: #666666; font-size: 12px; }
</style>
</head>
<body>
<div id="bar">
  Season <select id="season"><option>MK1</option><option>MH</option></select>
  Crop year <input id="year" type="number" min="__FIRST__" max="__LAST__" value="__YEAR__">
  Payout share:
  <span class="key" style="background:#fff7ec"></span>0
  <span class="key" style="background:#fdd49e"></span>above 0
  <span class="key" style="background:#fc8d59"></span>0.5
  <span class="key" style="background:#990000"></span>1
  <span class="key" style="background:#9ecae1"></span>no record
  <span class="key" style="background:#cccccc"></span>not insured
  <br><span id="note">Illustrative, not a priced insurance product. Rainfall: CHIRPS v3, Climate Hazards Center
  (CC BY 4.0). Boundaries: Badan Informasi Geospasial 2022.</span>
</div>
<div id="map"></div>
<script>
  const season = document.getElementById("season");
  const year = document.getElementById("year");
  const tiles = () => [location.origin + "/tiles/{z}/{x}/{y}.pbf?year=" + year.value + "&season=" + season.value];
  const map = new maplibregl.Map({
    container: "map", center: [110.4, -7.3], zoom: 6.2,
    style: {version: 8, sources: {}, layers: [{id: "bg", type: "background", paint: {"background-color": "#eef2f4"}}]}
  });
  map.on("load", () => {
    map.addSource("units", {type: "vector", tiles: tiles(), minzoom: 4, maxzoom: 10});
    map.addLayer({
      id: "units", type: "fill", source: "units", "source-layer": "units",
      paint: {
        "fill-color": ["case",
          ["!", ["get", "insured"]], "#cccccc",
          ["!", ["has", "payout_frac"]], "#9ecae1",
          ["interpolate", ["linear"], ["get", "payout_frac"], 0, "#fff7ec", 0.001, "#fdd49e", 0.5, "#fc8d59", 1, "#990000"]],
        "fill-outline-color": "#ffffff"
      }
    });
  });
  const reload = () => map.getSource("units").setTiles(tiles());
  season.addEventListener("change", reload);
  year.addEventListener("change", reload);
  map.on("click", "units", (e) => {
    const p = e.features[0].properties;
    const f = (v) => (v === undefined || v === null) ? "-" : Number(v).toFixed(3);
    const lines = p.insured
      ? [p.name, (p.season_label || "no record for this crop year") + (p.provisional ? " (provisional)" : ""),
         "index " + f(p.index_value) + ", trigger " + f(p.trigger_value) + ", exit " + f(p.exit_value),
         "payout share " + f(p.payout_frac)]
      : [p.name, "not an insured unit"];
    const box = document.createElement("div");
    lines.forEach((text) => { const line = document.createElement("div"); line.textContent = text; box.appendChild(line); });
    new maplibregl.Popup().setLngLat(e.lngLat).setDOMContent(box).addTo(map);
  });
</script>
</body>
</html>
"""
page = VIEWER.replace("__YEAR__", str(YEAR)).replace("__FIRST__", str(FIRST_YEAR)).replace("__LAST__", str(LAST_YEAR))
(WEBMAP / "index.html").write_text(page, encoding="utf-8")
print(f"map page written: {WEBMAP / 'index.html'} ({len(page):,} characters)")
map page written: E:\temp\pgci\webmap\index.html (3,397 characters)

The next cell starts the server and does what a browser would: it fetches the page, then every zoom-6 tile over Java’s bounding box, plus one far from Java and one out of range, and keeps the tiles for section 6. It stops the server again whatever happens in between (finally).

checks, served = [], {}
start_server()
try:
    with FETCH.open(f"http://127.0.0.1:{PORT}/", timeout=30) as response:
        checks.append(("/", response.status, response.headers["Content-Type"], len(response.read())))
    t = time.perf_counter()
    for z, x, y in java_tiles(6) + [(6, 0, 0)]:
        address = f"/tiles/{z}/{x}/{y}.pbf?year={YEAR}&season={SEASON}"
        with FETCH.open(f"http://127.0.0.1:{PORT}{address}", timeout=60) as response:
            served[(z, x, y)] = response.read()
            checks.append((address, response.status, response.headers["Content-Type"], len(served[(z, x, y)])))
    seconds = time.perf_counter() - t
    try:
        FETCH.open(f"http://127.0.0.1:{PORT}/tiles/6/64/0.pbf", timeout=30)
    except urllib.error.HTTPError as error:
        checks.append(("/tiles/6/64/0.pbf", error.code, "(error)", 0))
finally:
    stop_server()
print(f"{len(served)} tiles in {seconds:.1f} s, {sum(len(b) for b in served.values()):,} bytes in all")
pd.DataFrame(checks, columns=["address", "status", "content_type", "bytes"])
serving on http://127.0.0.1:8799/
server stopped
7 tiles in 2.2 s, 75,374 bytes in all
address status content_type bytes
0 / 200 text/html; charset=utf-8 3467
1 /tiles/6/50/32.pbf?year=2018&season=MK1 200 application/vnd.mapbox-vector-tile 577
2 /tiles/6/50/33.pbf?year=2018&season=MK1 200 application/vnd.mapbox-vector-tile 10350
3 /tiles/6/51/32.pbf?year=2018&season=MK1 200 application/vnd.mapbox-vector-tile 0
4 /tiles/6/51/33.pbf?year=2018&season=MK1 200 application/vnd.mapbox-vector-tile 49705
5 /tiles/6/52/32.pbf?year=2018&season=MK1 200 application/vnd.mapbox-vector-tile 386
6 /tiles/6/52/33.pbf?year=2018&season=MK1 200 application/vnd.mapbox-vector-tile 14356
7 /tiles/6/0/0.pbf?year=2018&season=MK1 200 application/vnd.mapbox-vector-tile 0
8 /tiles/6/64/0.pbf 400 (error) 0

Look before moving on. The page and the tiles should return status 200 with the right content type, and the tile out of range (column 64 at zoom 6, where columns run from 0 to 63) status 400. Row 32 of zoom 6 lies between the equator and about 5.6 degrees south, mostly Java Sea with a few small islands, so its tiles are tiny or empty; row 33 holds the main island, up to the tile of section 4. Tile 6/0/0, in the Arctic, is empty (0 bytes), which a map simply draws as nothing.

6. What the browser receives

The published site of this series cannot run the server, so this section shows instead, inside the notebook, that the bytes the server sent are a map. A vector tile is a small binary file in the protocol-buffer format: a list of fields, each starting with its number and a wire type that says how to read it (an integer, or a length followed by that many bytes). Integers are stored as varints, 7 bits per byte, the high bit meaning that another byte follows. The tile is a list of layers; each layer has lists of keys and values, and its features refer to them by position (tags); each feature’s geometry is a list of drawing commands in tile coordinates. The cell below shows the first numbers of one feature’s geometry.

def varint(buf: bytes, i: int) -> tuple[int, int]:
    """Read one protocol-buffer variable-length integer at position i; return it and the next position."""
    shift = result = 0
    while True:
        b = buf[i]
        i += 1
        result |= (b & 0x7F) << shift
        if b < 0x80:
            return result, i
        shift += 7


def fields(buf: bytes):
    """Yield (field number, value) for each field of one protocol-buffer message."""
    i = 0
    while i < len(buf):
        key, i = varint(buf, i)
        number, wire = key >> 3, key & 7
        if wire == 0:                                   # integer
            value, i = varint(buf, i)
        elif wire == 2:                                 # bytes: a string, a sub-message or packed integers
            n, i = varint(buf, i)
            value, i = buf[i:i + n], i + n
        elif wire == 1:                                 # 8 bytes (double)
            value, i = buf[i:i + 8], i + 8
        elif wire == 5:                                 # 4 bytes (float)
            value, i = buf[i:i + 4], i + 4
        else:
            raise ValueError(f"wire type {wire}")
        yield number, value


def packed(buf: bytes) -> list[int]:
    """A run of varints stored in one bytes field."""
    out, i = [], 0
    while i < len(buf):
        v, i = varint(buf, i)
        out.append(v)
    return out


def zigzag(n: int) -> int:
    """Undo the zig-zag encoding of signed integers (0, -1, 1, -2, ... stored as 0, 1, 2, 3, ...)."""
    return (n >> 1) ^ -(n & 1)


central = served[CENTRAL]
layer = next(v for n, v in fields(central) if n == 3)              # field 3 of a tile: a layer
feature = next(v for n, v in fields(layer) if n == 2)              # field 2 of a layer: a feature
geometry = next(packed(v) for n, v in fields(feature) if n == 4)   # field 4 of a feature: its geometry
first = geometry[:7]
print("first geometry numbers:", first)
print(f"{first[0]}: command {first[0] & 7} (1 = move to) repeated {first[0] >> 3} time(s); "
      f"then x {zigzag(first[1])}, y {zigzag(first[2])} from the tile's corner")
print(f"{first[3]}: command {first[3] & 7} (2 = line to) repeated {first[3] >> 3} times; "
      f"each step moves by (dx, dy), here first ({zigzag(first[4])}, {zigzag(first[5])})")
first geometry numbers: [9, 45, 496, 26, 6, 4, 1]
9: command 1 (1 = move to) repeated 1 time(s); then x -23, y 248 from the tile's corner
26: command 2 (2 = line to) repeated 3 times; each step moves by (dx, dy), here first (3, 2)

Each command number holds the command in its last three bits (& 7: 1 move to, 2 line to, 7 close the ring) and how many times it repeats in the rest (>> 3); every point after the first is stored as the step from the point before, in zig-zag form so that small steps in any direction are small numbers. The first point is measured from the tile’s top-left corner and can be negative, or beyond 4,096, when it lies in the buffer around the tile. The functions below finish the reader: they collect the keys and values of each layer and turn the commands into rings. You can run them without reading them line by line; they follow the Mapbox Vector Tile specification (see the references), and a map library such as MapLibre does the same in the browser.

def tile_value(buf: bytes):
    """One attribute value: string, float, double, integer or boolean."""
    for number, v in fields(buf):
        if number == 4:                                 # int64, stored in two's complement
            return v - (1 << 64) if v >> 63 else v
        return {1: lambda: v.decode(), 2: lambda: struct.unpack("<f", v)[0], 3: lambda: struct.unpack("<d", v)[0],
                5: lambda: v, 6: lambda: zigzag(v), 7: lambda: bool(v)}[number]()


def rings(commands: list[int]) -> list[list[tuple[int, int]]]:
    """Turn the drawing commands of a polygon into rings of (x, y) tile coordinates."""
    out, ring, x, y, i = [], [], 0, 0, 0
    while i < len(commands):
        command, count = commands[i] & 7, commands[i] >> 3
        i += 1
        if command == 7:                                # close the ring
            out.append(ring)
            ring = []
            continue
        for _ in range(count):                          # 1 = move to, 2 = line to
            x, y = x + zigzag(commands[i]), y + zigzag(commands[i + 1])
            i += 2
            ring.append((x, y))
    return out


def decode(tile: bytes) -> dict:
    """{layer name: (extent, [(attributes, rings), ...])} of a vector tile."""
    layers = {}
    for number, layer in fields(tile):
        if number != 3:
            continue
        name, keys, values, features, extent = None, [], [], [], 4096
        for n, v in fields(layer):
            if n == 1:
                name = v.decode()
            elif n == 2:
                features.append(v)
            elif n == 3:
                keys.append(v.decode())
            elif n == 4:
                values.append(tile_value(v))
            elif n == 5:
                extent = v
        decoded = []
        for feature in features:
            tags, geometry = [], []
            for n, v in fields(feature):
                if n == 2:
                    tags = packed(v)
                elif n == 4:
                    geometry = packed(v)
            attributes = {keys[tags[k]]: values[tags[k + 1]] for k in range(0, len(tags), 2)}
            decoded.append((attributes, rings(geometry)))
        layers[name] = (extent, decoded)
    return layers

The next cell decodes every zoom-6 tile the server sent and draws the units from the tiles alone, coloured by the payout_frac stored in them, with the same colours as the live map. No query to the database is made for this figure: it is drawn from what went over the wire. All tiles share one zoom and one extent, so their coordinates fit on one grid (column times 4,096 plus the coordinate inside the tile).

cmap = plt.get_cmap("OrRd")
fig, ax = plt.subplots(figsize=(10, 4))
units_seen, paying = {}, set()
for (z, x, y), tile in served.items():
    for name, (extent, features) in decode(tile).items():
        for attributes, polygon in features:
            units_seen[attributes["code"]] = attributes
            if attributes.get("payout_frac", 0) > 0:
                paying.add(attributes["code"])
            vertices, codes = [], []
            for ring in polygon:                       # tile coordinates to one pixel grid for all tiles
                vertices += [(x * extent + px, y * extent + py) for px, py in ring] + [(0, 0)]
                codes += [DrawPath.MOVETO] + [DrawPath.LINETO] * (len(ring) - 1) + [DrawPath.CLOSEPOLY]
            if not vertices:
                continue
            if not attributes["insured"]:
                colour = "0.8"
            elif "payout_frac" not in attributes:      # insured, but no payout record
                colour = "#9ecae1"
            else:
                colour = cmap(attributes["payout_frac"])
            ax.add_patch(PathPatch(DrawPath(vertices, codes), facecolor=colour, edgecolor="white", linewidth=0.2))
ax.autoscale_view()
ax.set_aspect("equal")
ax.invert_yaxis()                                      # tile rows count downward
ax.set_axis_off()
insured_seen = sum(1 for a in units_seen.values() if a["insured"])
ax.set_title(f"From {len(served)} served tiles: {SEASON} {YEAR}, {len(paying)} of {insured_seen} insured units pay "
             "(illustrative)")
fig.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(0, 1)), ax=ax, shrink=0.7,
             label="payout share of the sum insured")
plt.show()
print(f"layers: {sorted({n for t in served.values() for n in decode(t)})}; units in the tiles: {len(units_seen)}; "
      f"attributes of an insured unit: {sorted(next(a for a in units_seen.values() if a['insured']))}")

Map of Java's kabupaten and kota drawn only from the vector tiles sent by the local server, coloured by the payout share of the MK1 contract in crop year 2018, from none to full, with the units that are not insured in grey.

layers: ['units']; units in the tiles: 119; attributes of an insured unit: ['code', 'exit_value', 'index_value', 'insured', 'name', 'payout_frac', 'provisional', 'season_label', 'trigger_value']

Look before moving on. The figure should show Java with every kabupaten/kota, the insured units shaded by their payout and the others grey, though no table was read to draw it. The title counts the paying units, as Chapter 9 counted the units paying in each crop year. Neighbouring tiles overlap slightly at their edges, the buffer of 64 units that ST_AsMVTGeom keeps so that a map shows no seams.

7. Looking at the live map

To see the live map on your own computer, run the three steps below, each in a cell of its own. After a kernel restart, run the setup cell, the cells of sections 2 and 5 first (the page is already written). The section 5 cell that tests the server stops any running server at its end.

start_server()       # 1. start, then open the address it prints in a web browser
from IPython.display import IFrame
IFrame(f"http://127.0.0.1:{PORT}/", width=900, height=560)   # 2. optional, in Jupyter: the map inside the notebook
stop_server()        # 3. when you are done

Choose a season and a crop year at the top; click a unit for its numbers. The map needs internet access to load MapLibre; the tiles come from your own database.

The published site of this series is static: it was built from the executed notebooks and has no database or server behind it, so it cannot answer tile requests, and the figure of section 6, drawn from the served tiles, stands in for the live map.

8. What the series built

The map is the end of a chain of SQL that started with a rainfall raster and a paddy map (Chapter 1, section 5). Every step is a table, view or function in the database, built by a query you can read and run again. When new rainfall arrives, the views of Chapters 10 and 11 and this tile function follow by themselves; the tables of Chapters 4 to 9 (dekads, rain per unit, calendar, index, contract, payouts) are rebuilt by dropping them, latest first, and running their chapters again (Chapter 9, Troubleshooting), with the past left as it was (Chapter 8). The cell lists what the series created in its four schemas, and its largest tables.

summary = pd.read_sql("""
    SELECT n.nspname AS schema,
           count(*) FILTER (WHERE c.relkind IN ('r', 'p')) AS tables,
           count(*) FILTER (WHERE c.relkind = 'v') AS views,
           (SELECT count(*) FROM pg_proc f WHERE f.pronamespace = n.oid) AS functions,
           pg_size_pretty(sum(pg_total_relation_size(c.oid)) FILTER (WHERE c.relkind IN ('r', 'p'))) AS size
    FROM pg_namespace n LEFT JOIN pg_class c ON c.relnamespace = n.oid AND c.relkind IN ('r', 'p', 'v')
    WHERE n.nspname IN ('ref', 'raw', 'idx', 'out')
    GROUP BY n.oid, n.nspname ORDER BY array_position(ARRAY['ref', 'raw', 'idx', 'out'], n.nspname::text)""", ENGINE)
largest = pd.read_sql("""
    SELECT n.nspname || '.' || c.relname AS table_name, pg_size_pretty(pg_total_relation_size(c.oid)) AS size
    FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
    WHERE n.nspname IN ('ref', 'raw', 'idx', 'out') AND c.relkind IN ('r', 'p')
    ORDER BY pg_total_relation_size(c.oid) DESC LIMIT 5""", ENGINE)
print(largest.to_string(index=False))
summary
           table_name    size
    raw.paddy_moa2015 1555 MB
    ref.paddy_moa2015 1464 MB
 raw.chirps_rnl_daily  473 MB
raw.datanonkom_damage   98 MB
       idx.dekad_rain   53 MB
schema tables views functions size
0 ref 3 0 0 1547 MB
1 raw 4 0 0 2171 MB
2 idx 11 0 1 126 MB
3 out 1 4 3 1112 kB

Look before moving on. Most of the space is held by a few tables: the paddy polygons (Chapter 5) and the daily rainfall rasters (Chapter 4); the index, contract and payout tables built from them are small. The Summary below says how to free the space when you are done.

Checkpoint

The cell below checks, in a new session, what this chapter built:

  • both functions, STABLE and parallel safe, with the tile function returning bytea;
  • over the tiles that cover Java at zoom 6: each kabupaten/kota at most once per tile, every one of ref.kabupaten in some tile, and every insured unit with the payout value and index of out.payout for the season and crop year of the setup cell;
  • the provisional flag true only in the last crop year;
  • the tile of central Java not empty, holding as many features as it has rows with geometry, and a tile far from Java empty;
  • the map page in WEBMAP.

It depends on the setup cell and the tile helpers of sections 2 and 6.

with connect() as conn:
    first_row = lambda q, p=None: conn.execute(q, p).fetchone()
    kinds = dict(conn.execute("""SELECT p.proname, p.provolatile::text || p.proparallel::text || ' ' || format_type(p.prorettype, NULL)
                                 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
                                 WHERE n.nspname = 'out' AND p.proname IN ('payout_tile', 'payout_tile_features')""").fetchall())
    seen, duplicates, mismatches = set(), 0, 0
    for z, x, y in java_tiles(6):
        rows_now = conn.execute("""
            SELECT f.code, count(*) OVER (PARTITION BY f.code) AS n,
                   f.insured AND (f.payout_frac IS DISTINCT FROM p.payout_frac OR f.index_value IS DISTINCT FROM p.index_value)
            FROM out.payout_tile_features(%s, %s, %s, %s, %s) f
            LEFT JOIN out.payout p ON p.kabupaten_code = f.code AND p.season = %s AND p.crop_year = %s
            WHERE f.geom IS NOT NULL""", [z, x, y, YEAR, SEASON, SEASON, YEAR]).fetchall()
        seen |= {r[0] for r in rows_now}
        duplicates += sum(1 for r in rows_now if r[1] > 1)
        mismatches += sum(1 for r in rows_now if r[2])
    n_kab = first_row("SELECT count(*) FROM ref.kabupaten")[0]
    provisional_years = [r[0] for r in conn.execute("""
        SELECT DISTINCT y FROM generate_series(%s::integer, %s::integer) AS y,
             LATERAL out.payout_tile_features(%s, %s, %s, y, %s) f WHERE f.provisional""",
                                                     [FIRST_YEAR, LAST_YEAR, *CENTRAL, SEASON]).fetchall()]
    central_tile = first_row("SELECT out.payout_tile(%s, %s, %s, %s, %s)", [*CENTRAL, YEAR, SEASON])[0]
    central_rows = first_row("SELECT count(*) FROM out.payout_tile_features(%s, %s, %s, %s, %s) WHERE geom IS NOT NULL",
                             [*CENTRAL, YEAR, SEASON])[0]
    empty = first_row("SELECT length(out.payout_tile(6, 0, 0, %s, %s))", [YEAR, SEASON])[0]

assert kinds == {"payout_tile": "ss bytea", "payout_tile_features": "ss record"}, kinds
assert duplicates == 0 and mismatches == 0, f"{duplicates} duplicated rows, {mismatches} payouts differing from out.payout"
assert len(seen) == n_kab, f"{len(seen)} of {n_kab} kabupaten/kota in the tiles"
assert provisional_years in ([], [LAST_YEAR]), f"provisional crop years {provisional_years}"
assert len(central_tile) > 0 and len(decode(bytes(central_tile))["units"][1]) == central_rows, "central tile content"
assert empty == 0, f"tile 6/0/0 holds {empty} bytes"
assert (WEBMAP / "index.html").exists(), "map page missing"
print(f"checkpoint passed: {len(java_tiles(6))} zoom-6 tiles cover all {n_kab} kabupaten/kota, payouts equal to "
      f"out.payout; code cells took {time.perf_counter() - T0:.0f} s since the setup cell")
checkpoint passed: 6 zoom-6 tiles cover all 119 kabupaten/kota, payouts equal to out.payout; code cells took 14 s since the setup cell

Troubleshooting

Symptom Cause Fix
... is missing: run Chapters 3 to 9 first an earlier chapter has not been run run that chapter first
OSError: [WinError 10048] or Address already in use another program, or a server left running, holds PORT run stop_server(), or set another PORT in the setup cell and run the cells again; on Linux or macOS, also wait a minute after a stop
start_server() fails after the cells of section 5 were run again while a server was running the old server still holds the port restart the kernel and run the cells again
requests return 404 or another site’s pages another server answers on PORT set another PORT
the browser shows the page but no units the server was stopped, or the page was opened as a file rather than from the server run start_server() and open the address it prints, not the file
the page stays blank MapLibre could not be loaded from the CDN check the internet connection; the tiles themselves need none
Windows asks whether Python may use the network the firewall noticed a program that listens on a port the server listens on 127.0.0.1 only; allowing it or not does not matter for this computer
function st_tileenvelope(... margin ...) does not exist PostGIS older than 3.1 upgrade PostGIS (the series uses 3.7)

Summary

You now have:

  • out.payout_tile_features(z, x, y, crop_year, season): the rows of a map tile, one per kabupaten/kota, with its payout, index and thresholds, clipped to the tile;
  • out.payout_tile(z, x, y, crop_year, season): the same packed as a Mapbox Vector Tile, with the signature pg_tileserv looks for;
  • a small tile server in Python and a MapLibre map page in data_dir/webmap, to look at the payouts of any season and crop year on your own computer.

With this chapter the series is complete. Along the way it used PostGIS and PostgreSQL for each step of an index insurance contract:

  • boundaries and damage reports loaded and checked (Chapter 3), rainfall rasters loaded and summed (Chapter 4), paddy polygons reprojected and joined to units (Chapter 5);
  • rasters and polygons combined through a weight table (Chapter 6), seasons found with window functions (Chapter 7), deficits ranked against a fixed reference (Chapter 8);
  • a contract written as a SQL function (Chapter 9), its back-test and uncertainty in views and a bootstrap (Chapter 10), its basis risk against reported damage (Chapter 11), and its payouts served as a map (this chapter).

All payouts are illustrative, not a priced insurance product. To free the space when you are done, drop the database (DROP DATABASE crop_insurance_book; from another database, as in Chapter 2) and delete the folder data_dir.

What comes next

The series ends here. To take it further: serve out.payout_tile with pg_tileserv, a separate download, for a map that stays up; add a layer of the basis-risk rates of Chapter 11 on your own copy; or extend the record when CHC publishes new months, and watch the provisional crop year become final.

References