Source code: Groundwater monitoring from AGS4: hydrographs, groundwater level maps and the QGIS Temporal Controller

Runnable Python scripts, requirements and console output for the tutorial “Groundwater monitoring from AGS4: hydrographs, groundwater level maps and the…

Last updated

These are the exact scripts used to produce every figure and number in Groundwater monitoring from AGS4: hydrographs, groundwater level maps and the QGIS Temporal Controller. Download them, install the requirements into a fresh virtual environment and run them from this folder.

Written and tested by

Run it
python -m venv .venv
.venv\Scripts\activate # macOS/Linux: source .venv/bin/activate
pip install -r requirements.txt
python a417_ags.py

a417_ags.py

a417_ags.py
"""Download, merge and repair the A417 Missing Link ground investigation AGS4 data.
Shared by every part of the TechnicalGIS series "AGS data in GIS"; each part keeps an identical copy.
The British Geological Survey (BGS) holds AGS files donated by the ground investigation industry.
Its OGC API lists every borehole it can export (collection "agsboreholeindex"), and its AGS
File Utilities API exports those boreholes as AGS4 files, one ZIP per request. A request URL
can only carry so many borehole IDs, so we ask for them in batches of 40.
repair() applies the fixes worked through step by step in Part 1, so Parts 2 and 3 can start
from a clean, merged set of tables with load_clean().
Data: A417 Missing Link ground investigation (BGS deposited data item 173984; client Highways
England, contractor Geotechnical Engineering Ltd), from the BGS AGS download service under the
Open Government Licence v3.0. Contains British Geological Survey materials © UKRI 2026.
"""
import io
import time
import zipfile
from pathlib import Path
import pandas as pd
import requests
from python_ags4 import AGS4
ITEM = 173984 # BGS deposited data item: HE551505 A417 Missing Link GI
INDEX = "https://ogcapi.bgs.ac.uk/collections/agsboreholeindex/items"
EXPORT = "https://agsapi.bgs.ac.uk/v7/ags_export/"
BATCH = 40
UA = {"User-Agent": "TechnicalGIS-tutorial (https://www.technicalgis.com)"}
# Geological units met in the A417 logs, youngest at the top. Bedrock codes are BGS Lexicon codes
# (GEOL_BGS); rank gives the expected order down a borehole, and an undivided group spans the ranks of its
# formations (rank to last). Superficial deposits have rank 0.
UNITS = pd.DataFrame([
# code, name, group, rank, colour
("TOPS", "Topsoil", "Superficial", 0, "#5b4636"),
("MGR", "Made ground", "Superficial", 0, "#9e9e9e"),
("HEAD", "Head", "Superficial", 0, "#d9b77e"),
("SLIP", "Landslide deposits", "Superficial", 0, "#c98c5a"),
("WHL", "White Limestone Formation", "Great Oolite Group", 1, "#f7f1bd"),
("HMB", "Hampen Formation", "Great Oolite Group", 2, "#e4d79c"),
("GOG", "Great Oolite Group (undivided)", "Great Oolite Group", 1, "#eee3a6"),
("FE", "Fuller's Earth Formation", "Great Oolite Group", 3, "#9fb08f"),
("SALS", "Salperton Limestone Formation", "Inferior Oolite Group", 4, "#f4cd72"),
("ASLS", "Aston Limestone Formation", "Inferior Oolite Group", 5, "#e9b157"),
("BLPL", "Birdlip Limestone Formation", "Inferior Oolite Group", 6, "#d98f3e"),
("IOG", "Inferior Oolite Group (undivided)", "Inferior Oolite Group", 4, "#e6a855"),
("BDS", "Bridport Sand Formation", "Lias Group", 7, "#d2c48c"),
("WHM", "Whitby Mudstone Formation", "Lias Group", 8, "#7d93ab"),
("MRB", "Marlstone Rock Formation", "Lias Group", 9, "#b0703f"),
("DYS", "Dyrham Formation", "Lias Group", 10, "#a3b8cc"),
("CHAM", "Charmouth Mudstone Formation", "Lias Group", 11, "#55698a"),
("NR", "No recovery or not classified", "Other", 0, "#f2f2f2"),
], columns=["code", "name", "group", "rank", "colour"]).set_index("code")
UNITS["last"] = UNITS["rank"]
UNITS.loc[["GOG", "IOG"], "last"] = [3, 6]
# Where GEOL_BGS is blank, the project's own code (GEOL_GEOL) still tells us the unit.
FROM_GEOL = {"TOP": "TOPS", "MG": "MGR", "HDD": "HEAD", "GOG": "GOG", "IOG": "IOG", "SLIP": "SLIP"}
def borehole_index(item=ITEM):
"""Every borehole in one BGS deposited data item, from the BGS OGC API (GeoJSON)."""
r = requests.get(INDEX, params={"f": "json", "limit": 1000, "item_index_id": item}, headers=UA, timeout=120)
r.raise_for_status()
rows = [f["properties"] for f in r.json()["features"]]
return pd.DataFrame(rows).sort_values("bgs_loca_id").reset_index(drop=True)
def _get(url, params, tries=5):
for attempt in range(tries):
try:
r = requests.get(url, params=params, headers=UA, timeout=300)
r.raise_for_status()
return r
except requests.RequestException:
if attempt == tries - 1:
raise
time.sleep(10 * (attempt + 1))
def download(data_dir, item=ITEM):
"""Download the item's boreholes as AGS4 files, once. Returns the .ags paths in order."""
raw = Path(data_dir) / f"bgs_{item}"
raw.mkdir(parents=True, exist_ok=True)
if not list(raw.glob("*.ags")):
ids = borehole_index(item).bgs_loca_id.tolist()
for i in range(0, len(ids), BATCH):
r = _get(EXPORT, {"bgs_loca_id": ";".join(ids[i:i + BATCH])})
with zipfile.ZipFile(io.BytesIO(r.content)) as z:
for name in z.namelist():
(raw / f"batch{i // BATCH + 1:02d}_{Path(name).name}").write_bytes(z.read(name))
time.sleep(1)
return sorted(raw.glob("*.ags"))
def merge(paths):
"""Read several AGS4 files from one project and stack them, group by group.
Each table keeps its UNIT and TYPE rows (from the first file) followed by every DATA row;
rows repeated in every file (PROJ, TRAN, ABBR, DICT and so on) are kept once.
"""
tables, headings = {}, {}
for p in paths:
t, h = AGS4.AGS4_to_dataframe(str(p))
for group, df in t.items():
if group not in tables:
tables[group], headings[group] = df, list(h[group])
continue
headings[group] += [c for c in h[group] if c not in headings[group]]
tables[group] = pd.concat([tables[group], df[df.HEADING == "DATA"]], ignore_index=True)
for group, df in tables.items():
df = df.reindex(columns=headings[group]).fillna("")
tables[group] = df.drop_duplicates(ignore_index=True)
return tables, headings
def repair(tables, headings):
"""Apply the Part 1 fixes to merged A417 tables, in place, and return them."""
# Rule 1: a degree sign double-encoded as "Β°" (Greek capital beta + degree); the logs write "deg".
for df in tables.values():
df.replace("Β°", "deg", regex=True, inplace=True)
# Rule 10a: three DICT headings defined twice; keep the later, archive descriptions.
d = tables["DICT"]
tables["DICT"] = d[~d.duplicated(["HEADING", "DICT_TYPE", "DICT_GRP", "DICT_HDNG"], keep="last")
| (d.HEADING != "DATA")].reset_index(drop=True)
# Rules 7, 9, 19a, 19b: rename the BGS identifiers to valid user-defined headings and define them.
new_dict = []
for group, old, new, desc in [("PROJ", "BGS_PROJ_ID", "PROJ_BGSI", "BGS export project identifier"),
("LOCA", "BGS_LOCA_ID", "LOCA_BGSI", "BGS borehole index identifier")]:
tables[group] = tables[group].rename(columns={old: new})
tables[group].loc[tables[group].HEADING == "TYPE", new] = "X"
headings[group] = [new if c == old else c for c in headings[group]]
new_dict.append({"HEADING": "DATA", "DICT_TYPE": "HEADING", "DICT_GRP": group, "DICT_HDNG": new,
"DICT_STAT": "OTHER", "DICT_DTYP": "X", "DICT_DESC": desc})
# The *_TEXT columns hold the depths and diameters exactly as originally written ("0.50"), where the
# plain columns were reformatted ("0.5"). Put the original text back, restore the standard data type
# and drop the extra column.
std, _ = AGS4.AGS4_to_dataframe(str(Path(AGS4.__file__).parent / "Standard_dictionary_v4_0_3.ags"))
dtype = std["DICT"].query("DICT_TYPE == 'HEADING'").set_index(["DICT_GRP", "DICT_HDNG"]).DICT_DTYP
for group in list(tables):
df = tables[group]
for col in [c for c in headings[group] if c.endswith("_TEXT")]:
base = col[:-5]
data = df.HEADING == "DATA"
same = pd.to_numeric(df.loc[data, base]).round(6).equals(pd.to_numeric(df.loc[data, col]).round(6))
assert same, f"{group}.{col} disagrees with {base}"
df.loc[data, base] = df.loc[data, col]
df.loc[df.HEADING == "TYPE", base] = dtype[(group, base)]
tables[group] = df = df.drop(columns=col)
headings[group].remove(col)
# Rule 10c: in the child groups LOCA_ID was exported with TYPE "X", so it no longer matches the
# parent key in LOCA (TYPE "ID"). Restore the standard type.
for group, df in tables.items():
if group != "LOCA" and "LOCA_ID" in df:
df.loc[df.HEADING == "TYPE", "LOCA_ID"] = "ID"
tables["DICT"] = pd.concat([tables["DICT"], pd.DataFrame(new_dict)], ignore_index=True).fillna("")
# Rule 7 (only checkable once the headings above are defined): headings must follow the order of
# the standard dictionary, with the file's own DICT headings after them in DICT order.
own = tables["DICT"].query("HEADING == 'DATA' and DICT_TYPE == 'HEADING'")
defined = pd.concat([std["DICT"].query("DICT_TYPE == 'HEADING'"), own])
for group in tables:
listed = defined[defined.DICT_GRP == group].DICT_HDNG.drop_duplicates().tolist()
order = {h: i for i, h in enumerate(listed)}
headings[group] = ["HEADING"] + sorted(headings[group][1:], key=lambda h: order.get(h, len(order)))
tables[group] = tables[group][headings[group]]
tables["TRAN"].loc[tables["TRAN"].HEADING == "DATA", "TRAN_DESC"] += \
"; three BGS exports merged and repaired (TechnicalGIS AGS data in GIS, Part 1)"
return tables, headings
def write(tables, headings, ags_path, metadata):
"""Write a clean AGS4 file with the FILE folder AGS Rule 20 expects beside it."""
ags_path = Path(ags_path)
ags_path.parent.mkdir(parents=True, exist_ok=True)
AGS4.dataframe_to_AGS4(tables, headings, str(ags_path), warnings=False)
fset = ags_path.parent / "FILE" / "BGSFileSet01"
fset.mkdir(parents=True, exist_ok=True)
(fset / "BGS_download_metadata.txt").write_bytes(Path(metadata).read_bytes())
return ags_path
def numeric(tables):
"""DATA rows only, with numbers as numbers. python-ags4 reads the TYPE row to decide; it leaves
"U" (variable decimal places) as text, so convert those columns too."""
out = {}
for g, df in tables.items():
types = df[df.HEADING == "TYPE"].iloc[0]
n = AGS4.convert_to_numeric(df)
for col in types.index[types == "U"]:
n[col] = pd.to_numeric(n[col], errors="coerce")
out[g] = n
return out
def unit_code(geol):
"""One unit code per GEOL row: the BGS Lexicon code, else the project code, else NR."""
code = geol.GEOL_BGS.where(geol.GEOL_BGS != "", geol.GEOL_GEOL.map(FROM_GEOL))
return code.fillna("NR")
def in_order(codes):
"""True if a top-to-bottom list of bedrock unit codes never steps back to a younger unit."""
reached = 0
for code in codes:
if UNITS.at[code, "last"] < reached:
return False
reached = max(reached, UNITS.at[code, "rank"])
return True
def load_clean(data_dir):
"""Download (once), merge and repair the A417 data. Returns numeric DataFrames by group."""
tables, headings = repair(*merge(download(data_dir)))
out = numeric(tables)
out["GEOL"] = out["GEOL"].sort_values(["LOCA_ID", "GEOL_TOP"], ignore_index=True)
out["GEOL"]["UNIT"] = unit_code(out["GEOL"])
return out

groundwater_monitoring.py

groundwater_monitoring.py
"""Groundwater monitoring from AGS4: installations, dip readings, hydrographs and groundwater level maps.
Part 9 of the TechnicalGIS series "AGS data in GIS". It reads the monitoring installations (MONG) and the
readings (MOND) from the original AGS4 file the contractor deposited with the BGS for the A417 Missing Link
ground investigation, separates the water level dips from the water quality profiles, flags dry readings,
finds the geological unit each standpipe's response zone is in, draws hydrographs, maps the depth to
groundwater and the groundwater level, and writes the installations and every reading to a GeoPackage
ready for the QGIS Temporal Controller (see qgis_groundwater.py).
TechnicalGIS tutorial: https://www.technicalgis.com/tutorials/groundwater-monitoring-ags4-python-qgis/
Data: A417 Missing Link ground investigation (BGS deposited data item 173984; client Highways England,
contractor Geotechnical Engineering Ltd), from the BGS under the Open Government Licence v3.0.
Contains British Geological Survey materials © UKRI 2026.
Environment Agency LIDAR Composite DTM 1 m via the Defra WCS (Open Government Licence v3).
"""
import time
from importlib.metadata import version
from pathlib import Path
from urllib.parse import quote
import numpy as np
import pandas as pd
import geopandas as gpd
import requests
import rasterio
import matplotlib
matplotlib.use("Agg")
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from matplotlib.colors import LightSource
from matplotlib.lines import Line2D
from matplotlib.tri import TriAnalyzer, Triangulation
from python_ags4 import AGS4
from shapely.geometry import LineString
import a417_ags as A
plt.rcParams.update({"figure.dpi": 150, "savefig.bbox": "tight", "font.size": 9,
"figure.facecolor": "white", "axes.facecolor": "white"})
pd.set_option("display.width", 130)
DATA = Path("data"); DATA.mkdir(exist_ok=True)
OUT = Path("output"); OUT.mkdir(exist_ok=True)
UA = {"User-Agent": "TechnicalGIS-tutorial (https://www.technicalgis.com)"}
ORIGINAL = "Geodata file 1908.ags" # the contractor's AGS4 file, as deposited with the BGS
ACCESSIONS = "https://webservices.bgs.ac.uk/accessions"
AOI = (391_600, 212_800, 395_600, 216_800) # the same 4 x 4 km LIDAR window as Parts 2, 3, 6 and 8
RES = 5.0
WCS = ("https://environment.data.gov.uk/spatialdata/lidar-composite-digital-terrain-model-dtm-1m/wcs"
"?service=WCS&version=2.0.1&request=GetCoverage&format=image/tiff"
"&CoverageId=13787b9a-26a4-4775-8523-806d13af58fc__Lidar_Composite_Elevation_DTM_1m")
BGS = "BGS AGS data © UKRI (OGL v3)."
BGS_EA = "BGS AGS data © UKRI; LIDAR © Environment Agency (both OGL v3)."
DRY_TOL = 0.05 # a dip within 5 cm of the base of the pipe is a dry pipe
SPIKE = 3.0 # a reading 3 m out of step with both neighbours is a spike
SUMP = 0.75 # water within 75 cm of the base of the response zone
PIPE = ["LOCA_ID", "MONG_ID"]
def section(title):
print(f"\n=== {title} ===")
def fetch(url, path, kind=None, tries=6):
"""Download once and cache, backing off when a server is busy. kind: expected Content-Type prefix."""
if not path.exists():
for attempt in range(tries):
try:
r = requests.get(url, timeout=600, headers=UA)
r.raise_for_status()
if kind and not r.headers.get("Content-Type", "").startswith(kind):
raise requests.RequestException(f"unexpected content: {r.text[:200]}")
break
except requests.RequestException as err:
if attempt == tries - 1:
raise
wait = getattr(err.response, "headers", {}).get("Retry-After")
time.sleep(float(wait) if wait and wait.isdigit() else 20 * (attempt + 1))
path.write_bytes(r.content)
return path
print(f"geopandas {gpd.__version__} | rasterio {rasterio.__version__} | python-ags4 {version('python-ags4')}")
# ------------------------------------------------------------------ Step 1: the monitoring groups
section("Step 1: the monitoring installations and readings")
path = fetch(f"{ACCESSIONS}/download/{A.ITEM}?fileName={quote(ORIGINAL)}", DATA / ORIGINAL)
tables, headings = AGS4.AGS4_to_dataframe(str(path))
mon = A.numeric({g: tables[g] for g in ["MONG", "MOND"]})
mong, mond = mon["MONG"], mon["MOND"]
mond["MOND_RDNG"] = pd.to_numeric(mond.MOND_RDNG.astype(str).str.strip(), errors="coerce") # typed XN
mond["time"] = pd.to_datetime(mond.MOND_DTIM, errors="coerce")
print(f"MONG: {len(mong)} installations in {mong.LOCA_ID.nunique()} holes; types: "
+ ", ".join(f"{t or '(blank)'} {n}" for t, n in mong.MONG_TYPE.value_counts().items()))
print(f"MOND: {len(mond):,} readings from {mond.time.min():%d %b %Y} to {mond.time.max():%d %b %Y}")
kinds = mond.groupby(["MOND_TYPE", "MOND_UNIT"]).size().rename("rows").reset_index()
print(kinds.to_string(index=False))
ags = A.load_clean(DATA) # the repaired LOCA and GEOL from Part 1
loca = ags["LOCA"].set_index("LOCA_ID")
geol = ags["GEOL"][["LOCA_ID", "GEOL_TOP", "GEOL_BASE", "UNIT"]]
# ------------------------------------------------------------------ Step 2: water level dips, dry pipes and levels
section("Step 2: separate the water level dips and flag dry pipes")
wdep = mond[mond.MOND_TYPE.eq("WDEP")]
quality = wdep.MOND_REM.eq("Water quality monitoring level")
print(f"WDEP rows: {len(wdep):,}; {quality.sum():,} are the depths of water quality readings, "
f"in {wdep[quality].LOCA_ID.nunique()} holes")
dips = wdep[~quality].copy()
base = (mond[mond.MOND_TYPE.eq("DBSE")].groupby(PIPE + ["MOND_DTIM"], dropna=False).MOND_RDNG.first()
.rename("base"))
dips = dips.join(base, on=PIPE + ["MOND_DTIM"])
dips["base"] = dips.base.fillna(dips.MONG_DIS) # measured depth to the base of the pipe, else as installed
blank = dips[dips.MOND_RDNG.isna()]
print(f"{len(dips):,} dips; {len(blank)} with no reading. Remarks on those: "
+ ", ".join(f"{r!r} {n}" for r, n in blank.MOND_REM.replace("", "(none)").value_counts().items()))
dips = dips[dips.MOND_RDNG.notna()].rename(columns={"MOND_RDNG": "depth"})
dips["dry"] = dips.depth >= dips.base - DRY_TOL
dips = dips.join(loca[["LOCA_NATE", "LOCA_NATN", "LOCA_GL"]], on="LOCA_ID")
dips["level"] = dips.LOCA_GL - dips.depth
print(f"{len(dips):,} readings in {dips.groupby(PIPE, dropna=False).ngroups} pipes, "
f"{dips.time.min():%b %Y} to {dips.time.max():%b %Y}; {dips.dry.sum()} dry")
print("dry readings by pipe:", ", ".join(f"{l} {g} {n}" for (l, g), n in
dips[dips.dry].groupby(PIPE, dropna=False).size().items()))
dips = dips.sort_values(PIPE + ["time"])
step = dips.groupby(PIPE, dropna=False)["level"]
before, after = dips.level - step.shift(1), dips.level - step.shift(-1)
dips["spike"] = ~dips.dry & (before.abs() > SPIKE) & (after.abs() > SPIKE) & (np.sign(before) == np.sign(after))
print("out of step with the readings either side (kept, but left out of the statistics): "
+ ", ".join(f"{r.LOCA_ID} {r.time:%d %b %Y} ({(before[i] + after[i]) / 2:+.1f} m)"
for i, r in dips[dips.spike].iterrows()))
wet = dips[~dips.dry & ~dips.spike]
# ------------------------------------------------------------------ Step 3: what each pipe is measuring
section("Step 3: the response zone of each pipe and the unit it is in")
pipes = mong[~mong.MONG_TYPE.eq("ICM")].copy() # inclinometers measure movement, not water
swap = pipes.MONG_TRZ > pipes.MONG_BRZ
print("response zones entered upside down: " + ", ".join(pipes[swap].LOCA_ID))
pipes.loc[swap, ["MONG_TRZ", "MONG_BRZ"]] = pipes.loc[swap, ["MONG_BRZ", "MONG_TRZ"]].values
pipes["mid"] = (pipes.MONG_TRZ + pipes.MONG_BRZ) / 2
m = pipes.reset_index().merge(geol, on="LOCA_ID")
inside = m[(m.GEOL_TOP <= m.mid) & (m.mid < m.GEOL_BASE)].drop_duplicates("index").set_index("index")
pipes["UNIT"] = inside.UNIT.reindex(pipes.index).fillna("NR")
spans = m[(m.GEOL_BASE > m.MONG_TRZ) & (m.GEOL_TOP < m.MONG_BRZ)].groupby("index").UNIT.agg(
lambda s: "+".join(dict.fromkeys(s)))
pipes["units_spanned"] = spans.reindex(pipes.index).fillna("NR")
stats = wet.groupby(PIPE, dropna=False).agg(
readings=("level", "size"), first=("time", "min"), last=("time", "max"),
depth_median=("depth", "median"), level_median=("level", "median"),
level_min=("level", "min"), level_max=("level", "max"))
stats["range"] = stats.level_max - stats.level_min
pipes = pipes.join(stats, on=PIPE).join(loca[["LOCA_NATE", "LOCA_NATN", "LOCA_GL"]], on="LOCA_ID")
pipes = pipes[pipes.readings.notna()].copy()
pipes["readings"] = pipes.readings.astype(int)
pipes["dry_readings"] = dips[dips.dry].groupby(PIPE, dropna=False).size().reindex(
pd.MultiIndex.from_frame(pipes[PIPE])).fillna(0).astype(int).values
pipes["group"] = pipes.UNIT.map(A.UNITS.group)
pipes["zone_top_mOD"] = pipes.LOCA_GL - pipes.MONG_TRZ
pipes["zone_base_mOD"] = pipes.LOCA_GL - pipes.MONG_BRZ
pipes["at_base"] = pipes.depth_median > pipes.MONG_BRZ - SUMP # only ever water in the sump of the pipe
pipes["pipe"] = pipes.LOCA_ID + " " + pipes.MONG_ID.replace("", "?")
pipes = pipes.sort_values(["group", "LOCA_GL"]).reset_index(drop=True)
print(pipes.groupby("group").agg(pipes=("pipe", "size"), readings=("readings", "sum"),
median_depth=("depth_median", "median"), median_level=("level_median", "median"),
widest_range=("range", "max")).round(1).to_string())
print("water only ever in the bottom 75 cm of the response zone: "
+ ", ".join(f"{r.pipe} ({r.depth_median:.1f} of {r.MONG_BRZ:.1f} m)" for r in pipes[pipes.at_base].itertuples()))
GROUPS = {"Superficial": ("Landslide deposits", "#b5651d"), "Lias Group": ("Lias Group mudstones and sands", "#3d5a80"),
"Inferior Oolite Group": ("Inferior Oolite Group limestones", "#d1495b"),
"Great Oolite Group": ("Great Oolite Group\nand Fuller's Earth", "#2a9d8f"),
"Other": ("Not\nlogged", "#888888")}
pipes["group"] = pd.Categorical(pipes.group, list(GROUPS))
pipes = pipes.sort_values(["group", "LOCA_GL"]).reset_index(drop=True)
fig, ax = plt.subplots(figsize=(16, 6))
x, ticks = 0, []
for grp, g in pipes.groupby("group", observed=True):
start = x
for r in g.itertuples():
ax.plot([x, x], [r.LOCA_GL, r.zone_base_mOD], color="#bbbbbb", lw=1, zorder=1)
ax.add_patch(plt.Rectangle((x - 0.32, r.zone_base_mOD), 0.64, r.MONG_BRZ - r.MONG_TRZ,
fc=A.UNITS.colour.get(r.UNIT, "#f2f2f2"), ec="black", lw=0.6, zorder=2))
ax.plot([x - 0.45, x + 0.45], [r.LOCA_GL] * 2, color="black", lw=1.6, zorder=3)
ax.plot([x, x], [r.level_min, r.level_max], color="#1f6fb4", lw=2.2, zorder=4)
ax.scatter(x, r.level_median, marker="v", s=36, color="#1f6fb4", edgecolor="white", lw=0.5, zorder=5)
ticks.append((x, r.pipe))
x += 1
ax.text((start + x - 1) / 2, 302, GROUPS[grp][0], ha="center", va="bottom", fontsize=8.5,
color=GROUPS[grp][1], weight="bold")
x += 1.2
ax.set_xticks([t for t, _ in ticks], [p for _, p in ticks], rotation=90, fontsize=7)
ax.set_xlim(-1, x - 1)
ax.set_ylim(110, 300)
ax.set_ylabel("elevation (m OD)")
ax.grid(axis="y", color="#eeeeee")
ax.spines[["top", "right"]].set_visible(False)
units = [u for u in A.UNITS.index if u in set(pipes.UNIT)]
ax.legend(handles=[Line2D([], [], color="black", lw=1.6, label="ground level"),
Line2D([], [], color="#1f6fb4", lw=2.2, marker="v", mfc="#1f6fb4", mec="white",
label="median water level and\nlowest to highest reading")]
+ [plt.Rectangle((0, 0), 1, 1, fc=A.UNITS.colour[u], ec="black", lw=0.6,
label=f"response zone in {A.UNITS.name[u]}" if u != "NR" else "response zone not logged")
for u in units],
fontsize=7, frameon=False, loc="upper left", bbox_to_anchor=(1, 1))
ax.set_title("What each standpipe measures: response zone, geological unit and water levels", loc="left",
fontsize=10, weight="bold", pad=30)
fig.text(0.01, -0.07, BGS + " Unit at the middle of each response zone from GEOL; levels are ground level (LOCA_GL) "
"minus the dipped depth, dry and out-of-step readings excluded.", fontsize=7, color="#444444")
fig.savefig(OUT / "01-standpipe-response-zones.png")
plt.close(fig)
# ------------------------------------------------------------------ Step 4: hydrographs
section("Step 4: hydrographs")
wet = wet.merge(pipes[PIPE + ["pipe", "group", "level_median"]], on=PIPE)
wet["change"] = wet.level - wet.level_median
shown = [g for g in GROUPS if g != "Other"]
fig, axes = plt.subplots(len(shown), 1, figsize=(12, 10), sharex=True)
for ax, grp in zip(axes, shown):
g = wet[wet.group == grp]
for pipe, p in g.groupby("pipe"):
gap = p.time.diff() > pd.Timedelta(days=90) # break the line where monitoring paused
p = pd.concat([p, p[gap].assign(time=p.time[gap] - pd.Timedelta(days=1), change=np.nan)]).sort_values("time")
ax.plot(p.time, p.change, color=GROUPS[grp][1], lw=0.8, alpha=0.55, marker="o", ms=1.6)
monthly = g.set_index("time").change.resample("MS").median()
ax.plot(monthly.index + pd.Timedelta(days=14), monthly, color="black", lw=1.8)
s = dips[dips.spike].merge(pipes[PIPE + ["group", "level_median"]], on=PIPE)
s = s[s.group == grp]
ax.scatter(s.time, (s.level - s.level_median).clip(-6.2, 6.2), marker="x", color="black", s=22, lw=1, zorder=4)
ax.axhline(0, color="#999999", lw=0.6)
ax.set_ylim(-6.5, 6.5)
ax.set_ylabel("m from the\npipe's median")
ax.grid(color="#f0f0f0")
ax.spines[["top", "right"]].set_visible(False)
ax.set_title(f"{GROUPS[grp][0].replace(chr(10), ' ')}: {g['pipe'].nunique()} pipes, {len(g)} readings",
loc="left", fontsize=9.5,
color=GROUPS[grp][1], weight="bold")
peak = monthly.idxmax()
span = g.groupby("pipe").change.agg(lambda c: c.max() - c.min())
print(f"{grp:>22}: {g['pipe'].nunique():>2} pipes, highest monthly median {monthly.max():+.1f} m in {peak:%b %Y}, "
f"lowest {monthly.min():+.1f} m in {monthly.idxmin():%b %Y}; median range in a pipe {span.median():.1f} m")
axes[-1].xaxis.set_major_locator(mdates.MonthLocator(bymonth=[1, 4, 7, 10]))
axes[-1].xaxis.set_major_formatter(mdates.DateFormatter("%b\n%Y"))
fig.legend(handles=[Line2D([], [], color="#777777", lw=0.8, marker="o", ms=2, label="one standpipe"),
Line2D([], [], color="black", lw=1.8, label="monthly median of the group"),
Line2D([], [], ls="", marker="x", color="black", label="out-of-step reading")],
loc="upper right", bbox_to_anchor=(0.99, 1.0), ncol=3, fontsize=8, frameon=False)
fig.suptitle("A417 Missing Link: groundwater hydrographs by unit", weight="bold",
x=0.01, ha="left")
fig.text(0.01, -0.01, BGS + " Each line is a water level relative to that pipe's own median, so pipes at very "
"different elevations share one axis.", fontsize=7, color="#444444")
fig.tight_layout()
fig.savefig(OUT / "02-groundwater-hydrographs.png")
plt.close(fig)
# ------------------------------------------------------------------ Step 5: maps
section("Step 5: depth to groundwater and the groundwater level in the limestone")
X0, Y0, X1, Y1 = AOI
f = fetch(f"{WCS}&subset=E({X0},{X1})&subset=N({Y0},{Y1})&SCALEFACTOR={1 / RES}",
DATA / f"ea_dtm_{X0}_{Y0}_{X1 - X0}m_{RES:.0f}m.tif", "image/")
with rasterio.open(f) as src:
dtm = src.read(1).astype("float32")
dtm[dtm < -1000] = np.nan
extent = (src.bounds.left, src.bounds.right, src.bounds.bottom, src.bounds.top)
z = np.nan_to_num(dtm, nan=np.nanmin(dtm))
hs = LightSource(azdeg=315, altdeg=45).hillshade(z, dx=RES, dy=RES, vert_exag=1)
cx = np.linspace(extent[0] + RES / 2, extent[1] - RES / 2, z.shape[1])
cy = np.linspace(extent[3] - RES / 2, extent[2] + RES / 2, z.shape[0])
def basemap(ax, xlim, ylim):
ax.imshow(hs, cmap="gray", extent=extent, alpha=0.75)
ax.contour(cx, cy, z, levels=np.arange(110, 300, 10), colors="#6b6253", linewidths=0.3)
ax.set_xlim(*xlim)
ax.set_ylim(*ylim)
ax.set_aspect("equal")
ax.ticklabel_format(useOffset=False, style="plain")
ax.tick_params(labelsize=7)
ax.set_xlabel("Easting (m, British National Grid)")
ax.set_ylabel("Northing (m, British National Grid)")
BANDS = [0, 2, 5, 10, 20, 40, 90]
cmap = plt.get_cmap("viridis_r", len(BANDS) - 1)
norm = matplotlib.colors.BoundaryNorm(BANDS, cmap.N)
MARK = {"Superficial": "s", "Lias Group": "D", "Inferior Oolite Group": "o", "Great Oolite Group": "^",
"Other": "P"}
pad = 250
xlim = (pipes.LOCA_NATE.min() - pad, pipes.LOCA_NATE.max() + pad)
ylim = (pipes.LOCA_NATN.min() - pad, pipes.LOCA_NATN.max() + pad)
fig, ax = plt.subplots(figsize=(10, 9.2))
basemap(ax, xlim, ylim)
for grp, g in pipes.sort_values("depth_median", ascending=False).groupby("group", observed=True):
ax.scatter(g.LOCA_NATE, g.LOCA_NATN, c=g.depth_median, cmap=cmap, norm=norm, marker=MARK[grp],
s=40 + 14 * g.range.clip(upper=10), edgecolor="black", lw=0.7, zorder=3)
cb = fig.colorbar(matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, shrink=0.55, pad=0.02)
cb.set_label("median depth to water (m below ground)")
ax.legend(handles=[Line2D([], [], ls="", marker=MARK[g], mfc="white", mec="black", ms=7,
label=GROUPS[g][0].replace("\n", " "))
for g in GROUPS if g in set(pipes.group)]
+ [Line2D([], [], ls="", marker="o", mfc="white", mec="black", ms=s, label=t)
for s, t in [(5, "range under 1 m"), (11, "range 10 m or more")]],
title="response zone in", fontsize=7.5, title_fontsize=8, loc="lower left", framealpha=0.9)
ax.set_title("Median depth to groundwater in each standpipe, 2019 to 2021", loc="left", fontsize=10.5,
weight="bold")
fig.text(0.01, 0.02, BGS_EA + " Hillshade and 10 m contours from the 5 m LIDAR DTM. Symbol size grows with the "
"range of levels in the pipe.", fontsize=7, color="#444444")
fig.savefig(OUT / "03-depth-to-groundwater-map.png")
plt.close(fig)
for grp, g in pipes.groupby("group", observed=True):
print(f"{grp:>22}: depth to water {g.depth_median.min():.1f} to {g.depth_median.max():.1f} m, "
f"median {g.depth_median.median():.1f} m")
lime = pipes[pipes.UNIT.eq("BLPL")]
aq, low = lime[~lime.at_base], lime[lime.at_base]
tri = Triangulation(aq.LOCA_NATE, aq.LOCA_NATN)
tri.set_mask(TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio=0.05)) # drop sliver triangles at the edges
top = aq.nlargest(3, "level_median")
print(f"Birdlip Limestone: {len(aq)} pipes contoured, median levels {aq.level_median.min():.1f} to "
f"{aq.level_median.max():.1f} m OD; highest " + ", ".join(f"{r.LOCA_ID} {r.level_median:.1f}"
for r in top.itertuples()))
for name, cond in [("near the escarpment edge (north of 215,900 N, west of 393,500 E)",
(aq.LOCA_NATN > 215_900) & (aq.LOCA_NATE < 393_500)),
("on the plateau to the south-east (south of 215,400 N)", aq.LOCA_NATN < 215_400)]:
d = aq[cond]
print(f" {name}: {len(d)} pipes, {d.level_median.min():.1f} to {d.level_median.max():.1f} m OD")
print("left off the contours, water only in the sump: " + ", ".join(low["pipe"]))
step_m = 2
levels = np.arange(np.floor(aq.level_median.min() / step_m) * step_m, aq.level_median.max() + step_m, step_m)
pad = 300
xlim = (lime.LOCA_NATE.min() - pad, lime.LOCA_NATE.max() + pad)
ylim = (lime.LOCA_NATN.min() - pad, lime.LOCA_NATN.max() + pad)
fig, ax = plt.subplots(figsize=(9, 10))
basemap(ax, xlim, ylim)
filled = ax.tricontourf(tri, aq.level_median, levels=levels, cmap="Blues_r", alpha=0.6, zorder=2)
lines = ax.tricontour(tri, aq.level_median, levels=levels, colors="#08306b", linewidths=0.9, zorder=3)
ax.clabel(lines, fmt="%.0f", fontsize=7.5, inline_spacing=2)
ax.scatter(aq.LOCA_NATE, aq.LOCA_NATN, s=44, color="#d1495b", edgecolor="black", lw=0.7, zorder=4)
ax.scatter(low.LOCA_NATE, low.LOCA_NATN, s=44, facecolor="white", edgecolor="#d1495b", lw=1.5, zorder=4)
cluster = (lime.LOCA_NATN > 215_900) & (lime.LOCA_NATE < 393_500)
LABEL_LEFT = {"DSRC404", "DSRC311"} # labels that would sit on a neighbour's label if placed to the right
for r in lime[~cluster].itertuples():
text = f"{r.LOCA_ID}\n{'below ' if r.at_base else ''}{r.level_median:.1f}"
left = r.LOCA_ID in LABEL_LEFT
ax.annotate(text, (r.LOCA_NATE, r.LOCA_NATN), xytext=(-7 if left else 7, -10 if left else -3),
textcoords="offset points", ha="right" if left else "left", fontsize=6.5,
color="#222222", zorder=5, bbox=dict(fc="white", ec="none", alpha=0.7, pad=0.6))
c = lime[cluster]
ax.annotate(f"{len(c)} pipes at the escarpment edge:\n"
+ "\n".join(f"{r.LOCA_ID} {'below ' if r.at_base else ''}{r.level_median:.1f}"
for r in c.sort_values("LOCA_NATE").itertuples()),
(c.LOCA_NATE.mean(), c.LOCA_NATN.mean()), xytext=(xlim[0] + 60, ylim[0] + 250), fontsize=6.5,
color="#222222", zorder=5, bbox=dict(fc="white", ec="#999999", alpha=0.9, pad=3),
arrowprops=dict(arrowstyle="-", color="#555555", lw=0.8))
cb = fig.colorbar(filled, ax=ax, shrink=0.55, pad=0.02)
cb.set_label("median groundwater level (m OD)")
ax.legend(handles=[Line2D([], [], ls="", marker="o", mfc="#d1495b", mec="black", ms=7,
label="standpipe in the Birdlip Limestone"),
Line2D([], [], ls="", marker="o", mfc="white", mec="#d1495b", mew=1.5, ms=7,
label="water only in the bottom of the pipe:\nthe water table is below this level")],
fontsize=7.5, loc="upper right", framealpha=0.9)
ax.set_title("Groundwater level in the Birdlip Limestone (median of each pipe, 2 m contours)", loc="left",
fontsize=10, weight="bold")
fig.text(0.01, 0.02, BGS_EA + " Contours interpolated linearly between standpipes on a triangulation, thin edge "
"triangles removed.", fontsize=7, color="#444444")
fig.savefig(OUT / "04-limestone-groundwater-contours.png")
plt.close(fig)
# ------------------------------------------------------------------ Step 6: everything to a GeoPackage
section("Step 6: write the standpipes, readings and contours to a GeoPackage")
gpkg = OUT / "a417_groundwater.gpkg"
if gpkg.exists():
gpkg.unlink()
keep = ["pipe", "LOCA_ID", "MONG_ID", "MONG_TYPE", "MONG_TRZ", "MONG_BRZ", "zone_top_mOD", "zone_base_mOD", "UNIT",
"units_spanned", "group", "readings", "dry_readings", "first", "last", "depth_median", "level_median",
"level_min", "level_max", "range", "at_base", "LOCA_GL"]
standpipes = pipes.assign(group=pipes.group.astype(str), unit_name=pipes.UNIT.map(A.UNITS.name))
standpipes = gpd.GeoDataFrame(standpipes[keep + ["unit_name"]],
geometry=gpd.points_from_xy(pipes.LOCA_NATE, pipes.LOCA_NATN,
(pipes.zone_top_mOD + pipes.zone_base_mOD) / 2),
crs="EPSG:27700")
readings = dips.merge(pipes[PIPE + ["pipe", "group", "UNIT", "level_median"]], on=PIPE)
readings = readings.assign(group=readings.group.astype(str), change=readings.level - readings.level_median,
remark=readings.MOND_REM.fillna(""))
readings = gpd.GeoDataFrame(
readings[["pipe", "LOCA_ID", "MONG_ID", "time", "depth", "level", "change", "dry", "spike", "group", "UNIT",
"remark"]],
geometry=gpd.points_from_xy(readings.LOCA_NATE, readings.LOCA_NATN), crs="EPSG:27700")
segs = [(lvl, LineString(seg)) for lvl, ss in zip(lines.levels, lines.allsegs) for seg in ss if len(seg) > 1]
contours = gpd.GeoDataFrame({"level": [s[0] for s in segs]}, geometry=[s[1] for s in segs], crs="EPSG:27700")
for name, gdf in [("standpipes", standpipes), ("readings", readings), ("limestone_contours", contours)]:
gdf.to_file(gpkg, layer=name, driver="GPKG")
for name in ["standpipes", "readings", "limestone_contours"]:
check = gpd.read_file(gpkg, layer=name)
print(f"{gpkg.name} | {name}: {len(check)} {check.geom_type.iloc[0]} features in {check.crs.to_string()}"
+ (f", time {check.time.min():%Y-%m-%d} to {check.time.max():%Y-%m-%d}" if "time" in check else ""))
print("figures:", ", ".join(sorted(p.name for p in OUT.glob("0*.png"))))

qgis_groundwater.py

qgis_groundwater.py
"""Build a QGIS project that animates the A417 groundwater readings with the Temporal Controller.
Part 9 of the TechnicalGIS series "AGS data in GIS". Run groundwater_monitoring.py first, then run this with
the QGIS Python launcher, for example on Windows:
"C:\\Program Files\\QGIS 3.40.12\\bin\\python-qgis-ltr.bat" qgis_groundwater.py
It writes output/a417_groundwater.qgz (open it in QGIS Desktop and press play on the Temporal Controller) and
renders two frames of the animation side by side as output/05-qgis-temporal-frames.png.
Tested with QGIS 3.40.12-Bratislava.
Data: A417 Missing Link ground investigation (BGS deposited data item 173984), Open Government Licence
v3.0, contains British Geological Survey materials © UKRI 2026. Environment Agency LIDAR Composite DTM
(Open Government Licence v3).
"""
from pathlib import Path
from qgis.core import (
Qgis,
QgsApplication,
QgsClassificationRange,
QgsCoordinateReferenceSystem,
QgsDateTimeRange,
QgsGraduatedSymbolRenderer,
QgsHillshadeRenderer,
QgsLineSymbol,
QgsMapRendererParallelJob,
QgsMapSettings,
QgsMarkerSymbol,
QgsPalLayerSettings,
QgsProject,
QgsRasterDataProvider,
QgsRasterLayer,
QgsRectangle,
QgsSingleSymbolRenderer,
QgsRendererRange,
QgsTextBufferSettings,
QgsTextFormat,
QgsUnitTypes,
QgsVectorLayer,
QgsVectorLayerSimpleLabeling,
)
from qgis.PyQt.QtCore import QDate, QDateTime, QPoint, QRect, QSize, Qt, QTime
from qgis.PyQt.QtGui import QColor, QFont, QImage, QPainter
HERE = Path(__file__).parent
OUT = HERE / "output"
DTM = HERE / "data" / "ea_dtm_391600_212800_4000m_5m.tif"
GPKG = OUT / "a417_groundwater.gpkg"
CREDIT = ("Contains Environment Agency information © Environment Agency and database right; "
"BGS © UKRI (OGL v3)")
# Change from each pipe's own median level, in metres: falling water in orange, rising water in blue.
CLASSES = [(-99, -2, "#b35806", "more than 2 m below"), (-2, -0.5, "#f1a340", "0.5 to 2 m below"),
(-0.5, 0.5, "#f7f7f7", "within 0.5 m"), (0.5, 2, "#67a9cf", "0.5 to 2 m above"),
(2, 99, "#2166ac", "more than 2 m above")]
FRAMES = [("September 2020", QDate(2020, 9, 1), QDate(2020, 10, 1)),
("February 2021", QDate(2021, 2, 1), QDate(2021, 3, 1))]
def text_format(size, bold=False):
fmt = QgsTextFormat()
font = QFont("Arial")
font.setBold(bold)
fmt.setFont(font)
fmt.setSize(size)
buffer = QgsTextBufferSettings()
buffer.setEnabled(True)
buffer.setSize(0.8)
buffer.setColor(QColor("white"))
fmt.setBuffer(buffer)
return fmt
def main() -> None:
qgs = QgsApplication([], False)
qgs.initQgis()
print("QGIS", Qgis.version())
project = QgsProject.instance()
project.setCrs(QgsCoordinateReferenceSystem("EPSG:27700"))
dtm = QgsRasterLayer(str(DTM), "LIDAR DTM (hillshade)")
dtm.setRenderer(QgsHillshadeRenderer(dtm.dataProvider(), 1, 315, 45))
dtm.dataProvider().setZoomedInResamplingMethod(QgsRasterDataProvider.ResamplingMethod.Bilinear)
dtm.setOpacity(0.7)
contours = QgsVectorLayer(f"{GPKG}|layername=limestone_contours", "Birdlip Limestone groundwater (m OD)", "ogr")
pipes = QgsVectorLayer(f"{GPKG}|layername=standpipes", "Standpipes", "ogr")
# Dry and out-of-step readings are filtered in the layer source, so they never draw.
readings = QgsVectorLayer(f'{GPKG}|layername=readings|subset="dry" = 0 AND "spike" = 0',
"Water level readings", "ogr")
for layer in [dtm, contours, pipes, readings]:
print(f"{layer.name()}: valid={layer.isValid()}"
+ (f", {layer.featureCount()} features" if isinstance(layer, QgsVectorLayer) else ""))
contours.setRenderer(QgsSingleSymbolRenderer(
QgsLineSymbol.createSimple({"color": "#08306b", "width": "0.4"})))
label = QgsPalLayerSettings()
label.fieldName = "format_number(\"level\", 0)"
label.isExpression = True
label.placement = Qgis.LabelPlacement.Line
label.setFormat(text_format(6.5))
contours.setLabeling(QgsVectorLayerSimpleLabeling(label))
contours.setLabelsEnabled(True)
pipes.setRenderer(QgsSingleSymbolRenderer(QgsMarkerSymbol.createSimple(
{"name": "circle", "color": "0,0,0,0", "outline_color": "#333333", "outline_width": "0.3", "size": "4.2"})))
# Readings: one point per dip, coloured by the change from the pipe's median.
ranges = []
for lo, hi, colour, name in CLASSES:
symbol = QgsMarkerSymbol.createSimple({"name": "circle", "color": colour, "outline_color": "#222222",
"outline_width": "0.25", "size": "3.2"})
ranges.append(QgsRendererRange(QgsClassificationRange(name, lo, hi), symbol))
readings.setRenderer(QgsGraduatedSymbolRenderer("change", ranges))
# The temporal settings the Temporal Controller uses: each reading is an instant, so with monthly steps
# every frame shows the dips made in that month.
temporal = readings.temporalProperties()
temporal.setIsActive(True)
temporal.setMode(Qgis.VectorTemporalMode.FeatureDateTimeInstantFromField)
temporal.setStartField("time")
navigation = project.timeSettings()
navigation.setTemporalRange(QgsDateTimeRange(QDateTime(QDate(2019, 1, 1), QTime(0, 0)),
QDateTime(QDate(2021, 8, 1), QTime(0, 0))))
navigation.setTimeStep(1)
navigation.setTimeStepUnit(QgsUnitTypes.TemporalUnit.TemporalMonths)
navigation.setFramesPerSecond(2)
project.addMapLayers([dtm, contours, pipes, readings], False)
root = project.layerTreeRoot()
for layer in [readings, pipes, contours, dtm]: # first in the tree draws on top
root.addLayer(layer)
dtm.serverProperties().setAttribution("© Environment Agency, Open Government Licence v3")
for layer in [contours, pipes, readings]:
layer.serverProperties().setAttribution(
"Contains British Geological Survey materials © UKRI, Open Government Licence v3")
project.writeEntry("CopyrightLabel", "/Enabled", True)
project.writeEntry("CopyrightLabel", "/Label", CREDIT)
project.write(str(OUT / "a417_groundwater.qgz"))
print("saved output/a417_groundwater.qgz with temporal readings, monthly steps")
# Render two frames of the animation, the dry late summer of 2020 and the wet February of 2021.
size = QSize(900, 1100)
frames = []
for title, start, end in FRAMES:
settings = QgsMapSettings()
settings.setLayers([readings, pipes, contours, dtm])
settings.setDestinationCrs(project.crs())
settings.setExtent(QgsRectangle(392_000, 213_000, 395_000, 216_700))
settings.setOutputSize(size)
settings.setOutputDpi(150)
settings.setBackgroundColor(QColor("white"))
settings.setIsTemporal(True)
settings.setTemporalRange(QgsDateTimeRange(QDateTime(start, QTime(0, 0)), QDateTime(end, QTime(0, 0)),
True, False))
job = QgsMapRendererParallelJob(settings)
job.start()
job.waitForFinished()
shown = [f["change"] for f in readings.getFeatures() if start <= f["time"].date() < end]
below, above = sum(c <= -0.5 for c in shown), sum(c >= 0.5 for c in shown)
print(f"{title}: {len(shown)} readings in the frame, {below} more than 0.5 m below the pipe's median and "
f"{above} more than 0.5 m above; scale 1:{settings.scale():,.0f}; render errors: {len(job.errors())}")
frames.append((title, job.renderedImage(), len(shown)))
gap, legend_h = 20, 70
image = QImage(size.width() * 2 + gap, size.height() + legend_h, QImage.Format_ARGB32)
image.fill(QColor("white"))
painter = QPainter(image)
painter.setRenderHint(QPainter.Antialiasing)
for i, (title, frame, shown) in enumerate(frames):
x = i * (size.width() + gap)
painter.drawImage(x, 0, frame)
painter.setPen(QColor("#999999"))
painter.drawRect(x, 0, size.width() - 1, size.height() - 1)
painter.setFont(QFont("Arial", 11, QFont.Bold))
box = QRect(x + 10, 10, 420, 34)
painter.fillRect(box, QColor(255, 255, 255, 225))
painter.setPen(QColor("#111111"))
painter.drawText(box.adjusted(8, 0, 0, 0), Qt.AlignVCenter | Qt.AlignLeft,
f"{title}: {shown} readings")
painter.setFont(QFont("Arial", 8))
x, y = 12, size.height() + 14
painter.setPen(QColor("#111111"))
painter.drawText(x, y + 12, "Water level against the pipe's own median:")
x += painter.fontMetrics().horizontalAdvance("Water level against the pipe's own median:") + 16
for lo, hi, colour, name in CLASSES:
painter.setBrush(QColor(colour))
painter.setPen(QColor("#222222"))
painter.drawEllipse(QPoint(x + 6, y + 8), 6, 6)
painter.drawText(x + 18, y + 12, name)
x += painter.fontMetrics().horizontalAdvance(name) + 40
painter.setPen(QColor("#555555"))
painter.drawText(12, y + 40, CREDIT + ". Open circles: every standpipe. Lines: Birdlip Limestone "
"groundwater contours (m OD).")
painter.end()
image.save(str(OUT / "05-qgis-temporal-frames.png"))
print(f"rendered 05-qgis-temporal-frames.png, {image.width()} x {image.height()} px")
project.clear()
qgs.exitQgis()
if __name__ == "__main__":
main()