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