"""Laboratory classification data from AGS4: plasticity, grading and moisture content mapped by borehole and depth. Part 8 of the TechnicalGIS series "AGS data in GIS". The BGS export used in Parts 1 to 7 carries the field groups only, so this part downloads the original AGS4 file the contractor deposited with the BGS for the A417 Missing Link ground investigation. It reads the Atterberg limit (LLPL), moisture content (LNMC) and particle size (GRAG, GRAT) groups, finds the GEOL unit each specimen came from, classifies the fine soils on the BS 5930 plasticity chart, draws grading curves by unit, plots the index properties against elevation, maps the classification by borehole and depth, and writes everything to a GeoPackage for QGIS. TechnicalGIS tutorial: https://www.technicalgis.com/tutorials/ags-laboratory-classification-python/ 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.pyplot as plt from matplotlib.colors import LightSource from matplotlib.lines import Line2D from python_ags4 import AGS4 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", 120) 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 and 6 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)." KEYS = ["LOCA_ID", "SAMP_TOP", "SAMP_REF", "SAMP_TYPE", "SAMP_ID", "SPEC_REF", "SPEC_DPTH"] # BS 5930 plasticity chart: liquid limit ranges and their letters, and the A-line PI = 0.73 (LL - 20). LL_EDGES = [0, 35, 50, 70, 90, np.inf] LL_LETTERS = ["L", "I", "H", "V", "E"] LL_WORDS = ["low", "intermediate", "high", "very high", "extremely high"] CLASS_COLOURS = {"CL": "#c7e9b4", "CI": "#7fcdbb", "CH": "#2c7fb8", "CV": "#253494", "CE": "#081d58", "ML": "#fee391", "MI": "#fec44f", "MH": "#ec7014", "MV": "#993404", "ME": "#662506", "NP": "#ffffff"} # BS EN ISO 14688-1 particle size boundaries (mm) SIZES = {"clay": 0.002, "silt": 0.063, "sand": 2.0, "gravel": 63.0, "cobbles": 200.0} DEPTHS = [(0, 3, "0 to 3 m"), (3, 10, "3 to 10 m"), (10, 100, "more than 10 m")] 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 def plasticity_class(ll, pi): """BS 5930 symbol: C above the A-line, M below it, then the liquid limit letter. NP if non-plastic.""" if np.isnan(pi): return "NP" letter = LL_LETTERS[np.searchsorted(LL_EDGES, ll, side="right") - 1] return ("C" if pi >= 0.73 * (ll - 20) else "M") + letter def unit_legend(units): return [Line2D([], [], ls="", marker="o", mfc=A.UNITS.colour[u], mec="#333333", label=A.UNITS.name[u]) for u in units] print(f"geopandas {gpd.__version__} | rasterio {rasterio.__version__} | python-ags4 {version('python-ags4')}") # ------------------------------------------------------------------ Step 1: the original file and its lab groups section("Step 1: the deposited AGS4 file and its laboratory groups") path = fetch(f"{ACCESSIONS}/download/{A.ITEM}?fileName={quote(ORIGINAL)}", DATA / ORIGINAL) tables, headings = AGS4.AGS4_to_dataframe(str(path)) print(f"{path.name}: {path.stat().st_size / 1e6:.1f} MB, {len(tables)} groups, AGS " f"{tables['TRAN'].TRAN_AGS.iloc[-1]}, issue {tables['TRAN'].TRAN_ISNO.iloc[-1]}") lab = A.numeric({g: tables[g] for g in ["LLPL", "LNMC", "GRAG", "GRAT"]}) # numbers as numbers, as in Part 1 # The file types LNMC_MC as X (text) and LLPL_PL as XN (text or number), so convert those two by hand. for g, col in [("LNMC", "LNMC_MC"), ("LLPL", "LLPL_PL")]: raw = lab[g][col].astype(str).str.strip() lab[g][col] = pd.to_numeric(raw, errors="coerce") text = raw[lab[g][col].isna()].replace("", "(blank)").value_counts() print(f"{g}.{col}: {lab[g][col].notna().sum()} numbers; not numeric: " + ", ".join(f"{v!r} x{n}" for v, n in text.items())) for g, df in lab.items(): print(f" {g}: {len(df):>5} rows from {df.LOCA_ID.nunique():>2} holes") 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"]] missing = set(lab["LLPL"].LOCA_ID) - set(loca.index) print(f"LLPL holes missing from the repaired LOCA: {len(missing)}") # ------------------------------------------------------------------ Step 2: depth, position and unit of each specimen section("Step 2: where each specimen came from") def place(df): """Specimen depth (SPEC_DPTH, else the sample top), position, elevation and GEOL unit.""" df = df.copy() df["depth"] = df.SPEC_DPTH.fillna(df.SAMP_TOP) df = df.join(loca[["LOCA_NATE", "LOCA_NATN", "LOCA_GL"]], on="LOCA_ID") df["mOD"] = df.LOCA_GL - df.depth m = df.reset_index().merge(geol, on="LOCA_ID") m = m[(m.GEOL_TOP <= m.depth) & (m.depth < m.GEOL_BASE + 1e-6)].drop_duplicates("index").set_index("index") df["UNIT"] = m.UNIT.reindex(df.index).fillna("NR") return df ll = place(lab["LLPL"]).rename(columns={"LLPL_LL": "LL", "LLPL_PL": "PL", "LLPL_PI": "PI", "LLPL_425": "p425"}) mc = place(lab["LNMC"]).rename(columns={"LNMC_MC": "MC"}) grag = place(lab["GRAG"]) mc = mc[mc.MC.notna()] order = [u for u in A.UNITS.index if u in set(ll.UNIT) | set(mc.UNIT) | set(grag.UNIT)] table = pd.DataFrame({ "Atterberg": ll.UNIT.value_counts(), "moisture": mc.UNIT.value_counts(), "grading": grag.UNIT.value_counts(), "median_LL": ll.groupby("UNIT").LL.median(), "median_PI": ll.groupby("UNIT").PI.median(), "median_MC": mc.groupby("UNIT").MC.median()}).reindex(order) count_cols = ["Atterberg", "moisture", "grading"] table[count_cols] = table[count_cols].fillna(0).astype(int) table.index = [A.UNITS.name[u] for u in table.index] print(table.round(1).to_string(na_rep="-")) print(f"specimens from {ll.depth.min():.1f} to {ll.depth.max():.1f} m deep; " f"{(ll.LLPL_PREP.str.startswith('Washed')).sum()} of {len(ll)} Atterberg specimens washed on 425 µm") # ------------------------------------------------------------------ Step 3: the plasticity chart section("Step 3: the BS 5930 plasticity chart") ll["CLASS"] = [plasticity_class(a, b) for a, b in zip(ll.LL, ll.PI)] counts = ll.CLASS.value_counts() print("class counts:", ", ".join(f"{c} {n}" for c, n in counts.items())) print(f"{(ll.CLASS.str[0] == 'C').mean():.0%} plot above the A-line; {(ll.CLASS == 'NP').sum()} non-plastic " "(no plastic limit could be measured)") common = ll[ll.CLASS != "NP"].groupby("UNIT").CLASS.agg(lambda s: s.value_counts().index[0]) print("most common class by unit:") for u in [u for u in order if u in common.index]: print(f" {A.UNITS.name[u]:<30} {common[u]}") fig, ax = plt.subplots(figsize=(9, 6.2)) ax.plot([20, 120], [0, 73], color="black", lw=1.4) for e in LL_EDGES[1:-1]: ax.axvline(e, color="#999999", lw=0.7, ls="--") for (lo, hi), letter, word in zip(zip(LL_EDGES[:-1], [35, 50, 70, 90, 120]), LL_LETTERS, LL_WORDS): ax.text((lo + hi) / 2 if lo else 22, 84, f"{letter}\n{word}", ha="center", va="top", fontsize=7, color="#555555") ax.text(84, 0.73 * 64 - 1.5, "A-line: PI = 0.73 (LL − 20)", fontsize=7.5, ha="center", va="top", rotation=np.degrees(np.arctan(0.73)), rotation_mode="anchor", transform_rotates_text=True) ax.text(100, 30, "M: silts", fontsize=8, color="#555555") ax.text(62, 52, "C: clays", fontsize=8, color="#555555") units = [u for u in order if u in set(ll.UNIT)] for u in units: d = ll[(ll.UNIT == u) & ll.PI.notna()] ax.scatter(d.LL, d.PI, s=22, color=A.UNITS.colour[u], edgecolor="#333333", lw=0.4, zorder=3) np_ = ll[ll.PI.isna()] ax.scatter(np_.LL, np.zeros(len(np_)) + 1, marker="v", s=22, color="white", edgecolor="#333333", lw=0.6, zorder=3) ax.set_xlim(0, 120) ax.set_ylim(0, 85) ax.set_xlabel("liquid limit, LL (%)") ax.set_ylabel("plasticity index, PI (%)") ax.set_title(f"A417 Missing Link: {len(ll)} Atterberg limit tests from {ll.LOCA_ID.nunique()} holes on the " "BS 5930 plasticity chart", loc="left", fontsize=10, weight="bold") ax.legend(handles=unit_legend(units) + [Line2D([], [], ls="", marker="v", mfc="white", mec="#333", label="non-plastic (plotted at PI = 1)")], fontsize=7.5, frameon=False, loc="center left", bbox_to_anchor=(1, 0.5)) ax.spines[["top", "right"]].set_visible(False) fig.text(0.01, -0.02, BGS + " Specimens prepared on material passing 425 µm.", fontsize=7, color="#444444") fig.savefig(OUT / "01-plasticity-chart.png") plt.close(fig) # ------------------------------------------------------------------ Step 4: grading curves section("Step 4: grading curves by unit") grat = lab["GRAT"].dropna(subset=["GRAT_SIZE", "GRAT_PERP"]) curves = grat.merge(grag[KEYS + ["UNIT"]], on=KEYS, how="inner").sort_values(KEYS + ["GRAT_SIZE"]) print(f"{len(grat)} sieve and sedimentation points; {curves.groupby(KEYS).ngroups} curves matched to a GRAG " f"specimen; types: " + ", ".join(f"{t} {n}" for t, n in grat.GRAT_TYPE.value_counts().items())) summary = grag.groupby("UNIT")[["GRAG_GRAV", "GRAG_SAND", "GRAG_FINE"]].median().reindex( [u for u in order if u in set(grag.UNIT)]).round(0) summary.columns = ["gravel %", "sand %", "fines %"] summary.insert(0, "specimens", grag.UNIT.value_counts()) summary.index = [A.UNITS.name[u] for u in summary.index] print(summary.to_string()) panels = ["MGR", "HEAD", "SLIP", "FE", "BDS", "other"] fig, axes = plt.subplots(2, 3, figsize=(13, 7.5), sharex=True, sharey=True) for ax, u in zip(axes.flat, panels): sub = curves[curves.UNIT == u] if u != "other" else curves[~curves.UNIT.isin(panels)] for edge in SIZES.values(): ax.axvline(edge, color="#bbbbbb", lw=0.7) for _, c in sub.groupby(KEYS): ax.plot(c.GRAT_SIZE, c.GRAT_PERP, color=A.UNITS.colour[c.UNIT.iloc[0]], lw=1.1, alpha=0.85) n = sub.groupby(KEYS).ngroups name = "Other units" if u == "other" else A.UNITS.name[u] ax.set_title(f"{name} ({n} curves)", fontsize=9, loc="left", pad=16) ax.set_xscale("log") ax.set_xlim(0.0006, 200) ax.set_ylim(0, 102) ax.grid(axis="y", color="#eeeeee") ax.spines[["top", "right"]].set_visible(False) for ax in axes[0]: for (name, edge), lo in zip(SIZES.items(), [0.0006] + list(SIZES.values())): ax.text(np.sqrt(lo * edge), 104, name, ha="center", fontsize=7, color="#555555") for ax in axes[1]: ax.set_xlabel("particle size (mm, log scale)") for ax in axes[:, 0]: ax.set_ylabel("percentage passing (%)") other_units = [u for u in A.UNITS.index if u in set(curves.UNIT) - set(panels)] axes.flat[-1].legend(handles=[Line2D([], [], color=A.UNITS.colour[u], lw=2, label=A.UNITS.name[u]) for u in other_units], loc="upper left", fontsize=7, frameon=False) fig.suptitle("A417 Missing Link: particle size distribution curves by geological unit", weight="bold", x=0.01, ha="left") fig.text(0.01, -0.02, BGS + " Grey lines: BS EN ISO 14688-1 clay, silt, sand, gravel and cobble boundaries.", fontsize=7, color="#444444") fig.savefig(OUT / "02-grading-curves.png") plt.close(fig) # ------------------------------------------------------------------ Step 5: index properties against elevation section("Step 5: moisture content, plastic limit and liquid limit against elevation") print(f"moisture content: {len(mc)} tests from {mc.LOCA_ID.nunique()} holes, {mc.MC.min():.1f} to " f"{mc.MC.max():.1f}% (median {mc.MC.median():.1f}%)") pair = ll.merge(mc[KEYS + ["MC"]], on=KEYS, how="inner") print(f"{len(pair)} specimens have a moisture content and Atterberg limits on the same specimen") nearby = pd.merge_asof(mc.sort_values("depth"), ll.sort_values("depth")[["LOCA_ID", "depth", "PL", "LL"]], on="depth", by="LOCA_ID", direction="nearest", tolerance=1.0).dropna(subset=["PL"]) nearby["LI"] = (nearby.MC - nearby.PL) / (nearby.LL - nearby.PL) wet = nearby[nearby.LI > 0] print(f"within 1 m of an Atterberg test: {len(nearby)} moisture contents, liquidity index median " f"{nearby.LI.median():.2f}; {len(wet)} wetter than the plastic limit, from: " + ", ".join(f"{A.UNITS.name[u]} {n}" for u, n in wet.UNIT.value_counts().items())) fig, axes = plt.subplots(1, 3, figsize=(12, 6.5), sharey=True) for ax, (df, col, label) in zip(axes, [(mc, "MC", "moisture content, w (%)"), (ll, "PL", "plastic limit, PL (%)"), (ll, "LL", "liquid limit, LL (%)")]): for u in [u for u in order if u in set(df.UNIT)]: d = df[df.UNIT == u] ax.scatter(d[col], d.mOD, s=14, color=A.UNITS.colour[u], edgecolor="#333333", lw=0.3) ax.set_xlabel(label) ax.grid(color="#eeeeee") ax.spines[["top", "right"]].set_visible(False) axes[0].set_xlim(0, 70) axes[0].set_ylabel("elevation of specimen (m OD)") axes[1].set_xlim(0, 60) axes[2].set_xlim(0, 120) fig.subplots_adjust(left=0.07, right=0.97, wspace=0.12) fig.legend(handles=unit_legend([u for u in order if u in set(mc.UNIT) | set(ll.UNIT)]), loc="center left", bbox_to_anchor=(0.99, 0.5), fontsize=7.5, frameon=False) fig.suptitle("A417 Missing Link: index properties against elevation", weight="bold", x=0.01, ha="left") fig.text(0.01, -0.02, BGS, fontsize=7, color="#444444") fig.savefig(OUT / "03-index-properties-elevation.png") plt.close(fig) # ------------------------------------------------------------------ Step 6: classification by borehole and depth section("Step 6: the classification by borehole and depth") 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) soil = ll[ll.UNIT != "TOPS"] # topsoil is organic, so leave it out of the mapped classification holes = (ll.groupby("LOCA_ID").agg(tests=("LL", "size"), deepest=("depth", "max")) .join(loca[["LOCA_NATE", "LOCA_NATN", "LOCA_GL"]])) for lo, hi, label in DEPTHS: band = soil[(soil.depth >= lo) & (soil.depth < hi)] plastic = band[band.CLASS != "NP"].sort_values("LL").groupby("LOCA_ID").CLASS.last() holes[f"class_{lo}_{hi}m"] = plastic.reindex(holes.index) holes.loc[holes.index.isin(band.LOCA_ID) & holes[f"class_{lo}_{hi}m"].isna(), f"class_{lo}_{hi}m"] = "NP" found = holes[f"class_{lo}_{hi}m"].dropna() high = found.str[1].isin(["H", "V", "E"]) print(f"{label:>14}: {len(found):>2} holes tested, {high.sum():>2} reach high plasticity or above; " "most plastic: " + ", ".join(f"{c} {n}" for c, n in found.value_counts().items())) pad = 200 xlim = (holes.LOCA_NATE.min() - pad, holes.LOCA_NATE.max() + pad) ylim = (holes.LOCA_NATN.min() - pad, holes.LOCA_NATN.max() + pad) 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]) fig, axes = plt.subplots(1, 3, figsize=(16, 4.6), sharey=True) for ax, (lo, hi, label) in zip(axes, DEPTHS): 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) col = holes[f"class_{lo}_{hi}m"] ax.scatter(holes.LOCA_NATE[col.isna()], holes.LOCA_NATN[col.isna()], s=8, color="#777777", zorder=2) for c in CLASS_COLOURS: h = holes[col == c] ax.scatter(h.LOCA_NATE, h.LOCA_NATN, s=55, color=CLASS_COLOURS[c], edgecolor="black", lw=0.7, zorder=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_title(f"{label} below ground ({col.notna().sum()} holes)", loc="left", fontsize=9.5) axes[0].set_ylabel("Northing (m, British National Grid)") axes[1].set_xlabel("Easting (m, British National Grid)") present = [c for c in CLASS_COLOURS if c in set(holes.filter(like="class_").stack())] fig.legend(handles=[Line2D([], [], ls="", marker="o", ms=8, mfc=CLASS_COLOURS[c], mec="black", label=c) for c in present] + [Line2D([], [], ls="", marker="o", ms=4, mfc="#777777", mec="none", label="no test at\nthese depths")], title="most plastic\nspecimen", fontsize=8, loc="center left", bbox_to_anchor=(0.99, 0.5), frameon=False) fig.suptitle("A417 Missing Link: the most plastic soil in each borehole, by depth below ground", weight="bold", x=0.01, ha="left") fig.text(0.01, -0.03, BGS_EA + " Topsoil excluded. Hillshade and 10 m contours from the 5 m LIDAR DTM.", fontsize=7, color="#444444") fig.savefig(OUT / "04-plasticity-by-borehole-map.png") plt.close(fig) # A long section: every specimen at its easting and elevation, on a line for each hole from ground level down. fig, ax = plt.subplots(figsize=(13, 5.2)) for lid, r in holes.iterrows(): ax.plot([r.LOCA_NATE] * 2, [r.LOCA_GL, r.LOCA_GL - r.deepest], color="#aaaaaa", lw=0.6, zorder=1) ax.scatter(holes.LOCA_NATE, holes.LOCA_GL, marker="_", s=90, color="#3b3b3b", lw=1.5, zorder=2) for c in [c for c in CLASS_COLOURS if c in set(ll.CLASS)]: d = ll[ll.CLASS == c] ax.scatter(d.LOCA_NATE, d.mOD, s=26, color=CLASS_COLOURS[c], edgecolor="black", lw=0.5, zorder=3, label=c) ax.set_xlabel("Easting (m, British National Grid): Crickley Hill escarpment to the west, Cotswold plateau to the east") ax.set_ylabel("elevation (m OD)") ax.set_ylim(100, 300) ax.ticklabel_format(useOffset=False, style="plain") ax.grid(axis="y", color="#eeeeee") ax.legend(title="BS 5930 class", fontsize=7.5, frameon=False, loc="center left", bbox_to_anchor=(1, 0.5)) ax.spines[["top", "right"]].set_visible(False) ax.set_title("Plasticity class of every Atterberg specimen, by borehole and elevation", loc="left", fontsize=10, weight="bold") fig.text(0.01, -0.03, BGS + " Black dash: ground level at each hole; grey lines run down to the deepest specimen.", fontsize=7, color="#444444") fig.savefig(OUT / "05-plasticity-long-section.png") plt.close(fig) for name, cond in [("west of 393,100 E (escarpment)", ll.LOCA_NATE < 393_100), ("east of 393,100 E (plateau)", ll.LOCA_NATE >= 393_100)]: d = soil[cond.reindex(soil.index)] print(f" {name}: {len(d)} specimens below topsoil, median LL {d.LL.median():.0f}, " f"high plasticity or above {d.CLASS.str[1].isin(['H', 'V', 'E']).mean():.0%}") # ------------------------------------------------------------------ Step 7: the lab results for QGIS section("Step 7: write the results to a GeoPackage") gpkg = OUT / "a417_lab_classification.gpkg" if gpkg.exists(): gpkg.unlink() layers = { "atterberg": ll[["LOCA_ID", "depth", "mOD", "UNIT", "LL", "PL", "PI", "p425", "CLASS", "SPEC_DESC", "LOCA_NATE", "LOCA_NATN"]], "moisture": mc[["LOCA_ID", "depth", "mOD", "UNIT", "MC", "LOCA_NATE", "LOCA_NATN"]], "grading": grag[["LOCA_ID", "depth", "mOD", "UNIT", "GRAG_GRAV", "GRAG_SAND", "GRAG_SILT", "GRAG_CLAY", "GRAG_FINE", "LOCA_NATE", "LOCA_NATN"]], "holes": holes.reset_index(), } for name, df in layers.items(): df = df.assign(unit_name=df.UNIT.map(A.UNITS.name)) if "UNIT" in df else df zcol = df.mOD if "mOD" in df else df.LOCA_GL gdf = gpd.GeoDataFrame(df.drop(columns=["LOCA_NATE", "LOCA_NATN"]), geometry=gpd.points_from_xy(df.LOCA_NATE, df.LOCA_NATN, zcol), crs="EPSG:27700") gdf.to_file(gpkg, layer=name, driver="GPKG") for name in layers: check = gpd.read_file(gpkg, layer=name) print(f"{gpkg.name} | {name}: {len(check)} PointZ features in {check.crs.to_string()}") print("figures:", ", ".join(sorted(p.name for p in OUT.glob("0*.png"))))