Source code: Laboratory classification data from AGS4: plasticity charts, grading curves and maps in Python
Runnable Python scripts, requirements and console output for the tutorial “Laboratory classification data from AGS4: plasticity charts, grading curves…
Last updated
These are the exact scripts used to produce every figure and number in Laboratory classification data from AGS4: plasticity charts, grading curves and maps in Python. Download them, install the requirements into a fresh virtual environment and run them from this folder.
- a417_ags.py
- lab_classification.py
- requirements.txt
- console.txt: the console output recorded when we ran it
python -m venv .venv.venv\Scripts\activate # macOS/Linux: source .venv/bin/activatepip install -r requirements.txtpython a417_ags.pya417_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 AGSFile Utilities API exports those boreholes as AGS4 files, one ZIP per request. A request URLcan 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 startfrom a clean, merged set of tables with load_clean().
Data: A417 Missing Link ground investigation (BGS deposited data item 173984; client HighwaysEngland, contractor Geotechnical Engineering Ltd), from the BGS AGS download service under theOpen Government Licence v3.0. Contains British Geological Survey materials © UKRI 2026."""import ioimport timeimport zipfilefrom pathlib import Path
import pandas as pdimport requestsfrom python_ags4 import AGS4
ITEM = 173984 # BGS deposited data item: HE551505 A417 Missing Link GIINDEX = "https://ogcapi.bgs.ac.uk/collections/agsboreholeindex/items"EXPORT = "https://agsapi.bgs.ac.uk/v7/ags_export/"BATCH = 40UA = {"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 outlab_classification.py
"""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 fieldgroups only, so this part downloads the original AGS4 file the contractor deposited with the BGS for theA417 Missing Link ground investigation. It reads the Atterberg limit (LLPL), moisture content (LNMC) andparticle size (GRAG, GRAT) groups, finds the GEOL unit each specimen came from, classifies the fine soils onthe 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 timefrom importlib.metadata import versionfrom pathlib import Pathfrom urllib.parse import quote
import numpy as npimport pandas as pdimport geopandas as gpdimport requestsimport rasterioimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom matplotlib.colors import LightSourcefrom matplotlib.lines import Line2Dfrom 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 BGSACCESSIONS = "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 6RES = 5.0WCS = ("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 groupssection("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 1loca = 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 specimensection("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 chartsection("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 curvessection("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 elevationsection("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 depthsection("Step 6: the classification by borehole and depth")X0, Y0, X1, Y1 = AOIf = 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 classificationholes = (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 = 200xlim = (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 QGISsection("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"))))