"""What is dNBR? A worked example from the 2025 Dava and Carrbridge wildfires. Computes NBR before and after Scotland's largest recorded wildfire (28 June 2025) from Sentinel-2 L2A, differences them, removes the offset measured on unburned ground nearby, classifies the result with the USGS dNBR severity ranges and prints the arithmetic for one example pixel in each class. Imagery is streamed from the Microsoft Planetary Computer: no account or API key needed. Outputs go to ./output. """ from pathlib import Path import time import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.colors import BoundaryNorm, ListedColormap from matplotlib.patches import Patch import numpy as np import pandas as pd import planetary_computer import pystac_client import rasterio from pyproj import Transformer from rasterio.enums import Resampling from rasterio.windows import from_bounds from scipy import ndimage HERE = Path(__file__).parent OUT = HERE / "output" OUT.mkdir(exist_ok=True) STAC_URL = "https://planetarycomputer.microsoft.com/api/stac/v1" CRS = "EPSG:32630" # UTM zone 30N, the native grid of tile 30VVJ BOUNDS = (444_000, 6_350_000, 478_000, 6_376_000) # Dava Moor, Lochindorb and the Carrbridge side RES = 20 # B8A and B12 are 20 m bands HA_PER_PX = RES * RES / 10_000 PRE_DATE, POST_DATE = "2025-05-16", "2025-08-02" # the clearest scenes either side of the fire WIDTH = (BOUNDS[2] - BOUNDS[0]) // RES HEIGHT = (BOUNDS[3] - BOUNDS[1]) // RES # Key and Benson (2006) dNBR ranges, as published by USGS and UN-SPIDER CLASSES = [ ("Enhanced regrowth, high", -np.inf, -0.25, "#1a9641"), ("Enhanced regrowth, low", -0.25, -0.10, "#a6d96a"), ("Unburned", -0.10, 0.10, "#e8e8e8"), ("Low severity", 0.10, 0.27, "#fee08b"), ("Moderate-low severity", 0.27, 0.44, "#fdae61"), ("Moderate-high severity", 0.44, 0.66, "#f46d43"), ("High severity", 0.66, np.inf, "#7b3294"), ] CLEAR_SCL = [4, 5, 6, 7] # vegetation, not vegetated, water, unclassified CLOUD_SCL = [3, 8, 9, 10] # cloud shadow, cloud medium and high probability, thin cirrus PUBLISHED_HA = 11_827 # Scottish Fire and Rescue Service figure for the Dava and Carrbridge fires WATER_SCL = 6 PLACES = {"Lochindorb": (57.405, -3.708), "Dava": (57.432, -3.645), "Grantown-on-Spey": (57.330, -3.608)} def section(title: str) -> None: print(f"\n=== {title} ===") catalog = pystac_client.Client.open(STAC_URL, modifier=planetary_computer.sign_inplace) def find(date: str): items = catalog.search(collections=["sentinel-2-l2a"], datetime=date, query={"s2:mgrs_tile": {"eq": "30VVJ"}}).item_collection() return items[0] def read(item, band: str) -> np.ndarray: resampling = Resampling.nearest if band == "SCL" else Resampling.average with rasterio.Env(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR", GDAL_HTTP_MAX_RETRY=5): with rasterio.open(item.assets[band].href) as src: win = from_bounds(*BOUNDS, src.transform) return src.read(1, window=win, out_shape=(HEIGHT, WIDTH), resampling=resampling) def load(item) -> dict: # Processing baseline 04.00 and later add 1000 to every digital number offset = -1000 if float(item.properties["s2:processing_baseline"]) >= 4 else 0 s = {"SCL": read(item, "SCL")} for band in ("B8A", "B12", "B04", "B03", "B02"): s[band] = (read(item, band).astype("float32") + offset) / 10_000 # Buffer cloud and shadow by 200 m: their soft edges are not always flagged cloudy = ndimage.binary_dilation(np.isin(s["SCL"], CLOUD_SCL), iterations=10) s["clear"] = np.isin(s["SCL"], CLEAR_SCL) & (s["SCL"] != WATER_SCL) & ~cloudy s["NBR"] = (s["B8A"] - s["B12"]) / (s["B8A"] + s["B12"]) return s section("Sentinel-2 scenes") t0 = time.time() pre_item, post_item = find(PRE_DATE), find(POST_DATE) for label, it in (("pre-fire ", pre_item), ("post-fire", post_item)): print(f"{label} {it.datetime:%Y-%m-%d} {it.properties['platform']} tile {it.properties['s2:mgrs_tile']} " f"baseline {it.properties['s2:processing_baseline']} scene cloud {it.properties['eo:cloud_cover']:.1f}%") pre, post = load(pre_item), load(post_item) valid = pre["clear"] & post["clear"] print(f"grid {WIDTH} x {HEIGHT} pixels of {RES} m ({WIDTH * RES / 1000:.0f} x {HEIGHT * RES / 1000:.0f} km), {CRS}; " f"clear land on both dates {valid.mean():.1%}; read in {time.time() - t0:.0f} s") section("NBR and dNBR") dnbr_raw = np.where(valid, pre["NBR"] - post["NBR"], np.nan) seed = ndimage.binary_opening(np.nan_to_num(dnbr_raw) > 0.27 + np.nanmedian(dnbr_raw), iterations=1) lab, n = ndimage.label(seed) sizes = ndimage.sum(seed, lab, index=np.arange(1, n + 1)) scar = np.isin(lab, 1 + np.flatnonzero(sizes * HA_PER_PX >= 50)) ring = (ndimage.binary_dilation(scar, iterations=50) & ~ndimage.binary_dilation(scar, iterations=15) & valid) OFFSET = float(np.nanmedian(dnbr_raw[ring])) dnbr = dnbr_raw - OFFSET print(f"median NBR on clear land: pre-fire {np.nanmedian(pre['NBR'][valid]):.3f}, post-fire {np.nanmedian(post['NBR'][valid]):.3f}") print(f"unburned ring 300 m to 1 km outside the scar: {ring.sum() * HA_PER_PX:,.0f} ha, median dNBR {OFFSET:+.3f} " f"-> subtracted as the offset") section("USGS severity classes") edges = [c[2] for c in CLASSES[:-1]] cls = np.where(np.isfinite(dnbr), np.digitize(dnbr, edges), 255).astype("uint8") # Burn perimeter: connected areas of moderate-low severity or worse of at least 500 ha, # with small gaps closed and unburned islands inside the scar kept burned = ndimage.binary_opening((cls >= 4) & (cls < 255), iterations=1) lab, n = ndimage.label(burned) sizes = ndimage.sum(burned, lab, index=np.arange(1, n + 1)) perimeter = np.isin(lab, 1 + np.flatnonzero(sizes * HA_PER_PX >= 500)) perimeter = ndimage.binary_fill_holes(ndimage.binary_closing(perimeter, iterations=3)) water = (pre["SCL"] == WATER_SCL) | (post["SCL"] == WATER_SCL) perimeter &= ~water rows = [] for i, (name, lo, hi, _) in enumerate(CLASSES): rng = f"< {hi:.2f}" if lo == -np.inf else (f">= {lo:.2f}" if hi == np.inf else f"{lo:.2f} to {hi:.2f}") rows.append({"class": name, "dNBR range": rng, "inside perimeter (ha)": round(((cls == i) & perimeter).sum() * HA_PER_PX, 1)}) table = pd.DataFrame(rows) burn_ha = perimeter.sum() * HA_PER_PX table["% of burn"] = (100 * table["inside perimeter (ha)"] / burn_ha).round(1) print(table.to_string(index=False)) masked = (perimeter & (cls == 255)).sum() * HA_PER_PX print(f"burn perimeter: {burn_ha:,.0f} ha ({burn_ha / PUBLISHED_HA:.0%} of the published {PUBLISHED_HA:,} ha); " f"{masked:,.0f} ha of it under cloud on one date") table.to_csv(OUT / "severity_area.csv", index=False) section("Worked example: one pixel per class") to_utm = Transformer.from_crs("EPSG:4326", CRS, always_xy=True) to_ll = Transformer.from_crs(CRS, "EPSG:4326", always_xy=True) examples = [] for i in (2, 3, 4, 5, 6): m = (cls == i) & perimeter if i > 2 else ring vals = dnbr[m] target = np.median(vals) rr, cc = np.where(m) k = np.argmin(np.abs(vals - target)) r, c = rr[k], cc[k] x, y = BOUNDS[0] + (c + 0.5) * RES, BOUNDS[3] - (r + 0.5) * RES lon, lat = to_ll.transform(x, y) e = dict(cls=CLASSES[i][0], lat=lat, lon=lon, nir_pre=pre["B8A"][r, c], swir_pre=pre["B12"][r, c], nir_post=post["B8A"][r, c], swir_post=post["B12"][r, c], nbr_pre=pre["NBR"][r, c], nbr_post=post["NBR"][r, c], raw=dnbr_raw[r, c], dnbr=dnbr[r, c], x=x, y=y) examples.append(e) print(f"{e['cls']:<23} {lat:.4f} N {abs(lon):.4f} W | pre B8A {e['nir_pre']:.4f} B12 {e['swir_pre']:.4f} " f"NBR {e['nbr_pre']:+.3f} | post B8A {e['nir_post']:.4f} B12 {e['swir_post']:.4f} NBR {e['nbr_post']:+.3f} " f"| dNBR {e['raw']:+.3f} - ({OFFSET:+.3f}) = {e['dnbr']:+.3f}") pd.DataFrame(examples).drop(columns=["x", "y"]).round(4).to_csv(OUT / "example_pixels.csv", index=False) section("Figures") EXTENT = (BOUNDS[0], BOUNDS[2], BOUNDS[1], BOUNDS[3]) def false_colour(s): rgb = np.dstack([s["B12"], s["B8A"], s["B04"]]) return np.clip(rgb / np.array([0.30, 0.40, 0.12]), 0, 1) def km_axes(ax, title): ax.set_title(title, fontsize=11, loc="left") ticks_x = np.arange(445_000, 478_001, 5_000) ticks_y = np.arange(6_350_000, 6_376_001, 5_000) ax.set_xticks(ticks_x, [f"{t / 1000:.0f}" for t in ticks_x], fontsize=8) ax.set_yticks(ticks_y, [f"{t / 1000:.0f}" for t in ticks_y], fontsize=8) ax.set_xlabel("Easting, km (UTM 30N)", fontsize=8) for name, (lat, lon) in PLACES.items(): px, py = to_utm.transform(lon, lat) ax.plot(px, py, "o", ms=3.5, mfc="white", mec="black", mew=0.8) ax.annotate(name, (px, py), xytext=(4, 4), textcoords="offset points", fontsize=8, color="black", bbox=dict(boxstyle="round,pad=0.15", fc="white", ec="none", alpha=0.75)) fig, axes = plt.subplots(1, 3, figsize=(16, 5.4), constrained_layout=True) axes[0].imshow(false_colour(pre), extent=EXTENT) km_axes(axes[0], f"Before: {PRE_DATE} (SWIR2, NIR, red)") axes[0].set_ylabel("Northing, km (UTM 30N)", fontsize=8) axes[1].imshow(false_colour(post), extent=EXTENT) km_axes(axes[1], f"After: {POST_DATE} (SWIR2, NIR, red)") cmap = ListedColormap([c[3] for c in CLASSES] + ["#5b8fd6"]) shown = np.where(cls == 255, 7, cls).astype(float) shown[(cls == 255) & ~((pre["SCL"] == WATER_SCL) | (post["SCL"] == WATER_SCL))] = np.nan axes[2].imshow(shown, cmap=cmap, norm=BoundaryNorm(np.arange(-0.5, 8.5), cmap.N), extent=EXTENT, interpolation="nearest") axes[2].contour(perimeter.astype(float), levels=[0.5], colors="black", linewidths=0.9, extent=(BOUNDS[0], BOUNDS[2], BOUNDS[3], BOUNDS[1])) km_axes(axes[2], "dNBR severity (USGS classes)") handles = ([Patch(fc=c[3], ec="#777", lw=0.4, label=c[0]) for c in CLASSES[2:]] + [Patch(fc="#5b8fd6", label="Water")] + [plt.Line2D([], [], color="black", lw=0.9, label="Burn perimeter")]) axes[2].legend(handles=handles, loc="upper left", fontsize=7.5, framealpha=0.9) fig.savefig(OUT / "01-dava-before-after-severity.png", dpi=130) plt.close(fig) # Why NBR works: mean reflectance of burned and unburned pixels, before and after hi = (cls == 6) & perimeter fig, ax = plt.subplots(figsize=(9, 4.6), constrained_layout=True) groups = [("Unburned moorland", ring), ("High-severity burn", hi)] w = 0.18 for g, (name, m) in enumerate(groups): vals = [np.nanmean(pre["B8A"][m]), np.nanmean(post["B8A"][m]), np.nanmean(pre["B12"][m]), np.nanmean(post["B12"][m])] for j, (v, col, hatch) in enumerate(zip(vals, ["#2b8cbe", "#a6bddb", "#d95f0e", "#fdbe85"], ["", "//", "", "//"])): x = g + (j - 1.5) * w ax.bar(x, v, w * 0.92, color=col, hatch=hatch, edgecolor="white") ax.text(x, v + 0.004, f"{v:.3f}", ha="center", va="bottom", fontsize=8) ax.set_xticks([0, 1], [g[0] for g in groups]) ax.set_ylabel("Surface reflectance") ax.legend(handles=[Patch(fc="#2b8cbe", label="NIR (B8A), before"), Patch(fc="#a6bddb", hatch="//", label="NIR (B8A), after"), Patch(fc="#d95f0e", label="SWIR2 (B12), before"), Patch(fc="#fdbe85", hatch="//", label="SWIR2 (B12), after")], fontsize=8, ncol=2, loc="upper right") ax.set_title("Fire lowers NIR and raises SWIR2, so NBR falls", fontsize=11, loc="left") ax.spines[["top", "right"]].set_visible(False) fig.savefig(OUT / "02-nir-swir2-before-after.png", dpi=130) plt.close(fig) # dNBR histogram with the class ranges behind it fig, ax = plt.subplots(figsize=(9, 4.2), constrained_layout=True) v = dnbr[np.isfinite(dnbr) & (perimeter | ring)] for name, lo, hi_, col in CLASSES: ax.axvspan(max(lo, -0.5), min(hi_, 1.3), color=col, alpha=0.55, lw=0) ax.hist(v, bins=np.arange(-0.5, 1.3, 0.02), color="#333", alpha=0.85) for t in edges[1:]: ax.axvline(t, color="white", lw=1) ax.set_xlim(-0.5, 1.3) ax.set_xlabel("dNBR (offset removed)") ax.set_ylabel("Pixels (20 m)") ax.set_title("dNBR inside the burn perimeter and on the unburned ground around it", fontsize=11, loc="left") ax.legend(handles=[Patch(fc=c[3], alpha=0.55, label=c[0]) for c in CLASSES[1:]], fontsize=7.5, loc="upper right") ax.spines[["top", "right"]].set_visible(False) fig.savefig(OUT / "03-dnbr-histogram-classes.png", dpi=130) plt.close(fig) print("saved 01-dava-before-after-severity.png, 02-nir-swir2-before-after.png, 03-dnbr-histogram-classes.png")