{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "71d35c78",
   "metadata": {},
   "source": [
    "# Lagos Urban Heat Island, 2019–2025 (observed) → 2027, 2029 (projected)\n",
    "\n",
    "**Landsat 8/9 C2 L2 land surface temperature (LST) · Dynamic World built-up · 20 LGAs**\n",
    "\n",
    "| Epoch | Imagery window (dry season, December-centred) | Status |\n",
    "|---|---|---|\n",
    "| 2019 | 1 Nov 2019 – 29 Feb 2020 | observed (baseline) |\n",
    "| 2021 | 1 Nov 2021 – 28 Feb 2022 | observed |\n",
    "| 2023 | 1 Nov 2023 – 29 Feb 2024 | observed |\n",
    "| 2025 | 1 Nov 2025 – 28 Feb 2026 | observed |\n",
    "| 2027 | — | projected (scenarios) |\n",
    "| 2029 | — | projected (scenarios) |\n",
    "\n",
    "Key metric: **heat excess** = mean LST of an area − mean LST of vegetated land in Lagos State *in the same epoch*.\n",
    "Both terms share the same weather, so heat excess is comparable across years in a way raw LST is not.\n",
    "\n",
    "Run top to bottom in Google Colab. Output: `uhi_outputs.zip` → unzip into the repo root\n",
    "(fills `docs/data/` for the web map and `results/figures/` for the README)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "785a528e",
   "metadata": {},
   "source": [
    "## 1. Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aeb71c87",
   "metadata": {},
   "outputs": [],
   "source": [
    "EE_PROJECT = \"your-ee-project-id\"       # Earth Engine Cloud project (non-commercial)\n",
    "\n",
    "EPOCHS = [\n",
    "    {\"id\": \"2019\", \"year\": 2019, \"start\": \"2019-11-01\", \"end\": \"2020-03-01\", \"label\": \"Dec 2019 (Nov–Feb)\"},\n",
    "    {\"id\": \"2021\", \"year\": 2021, \"start\": \"2021-11-01\", \"end\": \"2022-03-01\", \"label\": \"Dec 2021 (Nov–Feb)\"},\n",
    "    {\"id\": \"2023\", \"year\": 2023, \"start\": \"2023-11-01\", \"end\": \"2024-03-01\", \"label\": \"Dec 2023 (Nov–Feb)\"},\n",
    "    {\"id\": \"2025\", \"year\": 2025, \"start\": \"2025-11-01\", \"end\": \"2026-03-01\", \"label\": \"Dec 2025 (Nov–Feb)\"},\n",
    "]\n",
    "OBS_YEARS = [e[\"year\"] for e in EPOCHS]\n",
    "BASE_YEAR = OBS_YEARS[-1]                  # projections start from the latest observed epoch\n",
    "PROJECTION_YEARS = [2027, 2029]\n",
    "# Dynamic World built-up: annual mode for the calendar year of each epoch\n",
    "DW_WINDOWS = {y: (f\"{y}-01-01\", f\"{y + 1}-01-01\") for y in OBS_YEARS}\n",
    "\n",
    "MAX_SCENE_CLOUD = 40              # % scene cloud cover filter (pixel mask applied after)\n",
    "MIN_CLEAR_OBS = 3                 # minimum clear observations per pixel\n",
    "LST_VALID_RANGE = (10, 70)        # °C plausibility filter\n",
    "SCALE = 30                        # m\n",
    "COVERAGE_MIN_LGA = 0.30           # LGA-epoch rows with <30% valid land pixels are excluded from modelling\n",
    "HOTSPOT_PERCENTILE = 90           # hotspot = heat excess >= baseline-epoch 90th percentile\n",
    "BOOTSTRAP_N = 2000\n",
    "SEED = 42\n",
    "PNG_DIMENSIONS = 1600\n",
    "\n",
    "VEG_REF = [1, 2, 4, 5]            # Dynamic World: trees, grass, crops, shrub & scrub (flooded veg excluded)\n",
    "PAL_LST = [\"313695\", \"4575b4\", \"74add1\", \"abd9e9\", \"fee090\", \"fdae61\", \"f46d43\", \"d73027\", \"a50026\"]\n",
    "PAL_DIV = [\"2166ac\", \"67a9cf\", \"d1e5f0\", \"f7f7f7\", \"fddbc7\", \"ef8a62\", \"b2182b\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3846c5a4",
   "metadata": {},
   "source": [
    "## 2. Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f2b8eb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json, os, shutil, datetime as dt\n",
    "import numpy as np\n",
    "import requests\n",
    "import ee\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "try:\n",
    "    ee.Initialize(project=EE_PROJECT)\n",
    "except Exception:\n",
    "    ee.Authenticate()\n",
    "    ee.Initialize(project=EE_PROJECT)\n",
    "\n",
    "OUT = \"uhi_outputs\"\n",
    "DATA = os.path.join(OUT, \"docs\", \"data\")\n",
    "FIGS = os.path.join(OUT, \"results\", \"figures\")\n",
    "os.makedirs(DATA, exist_ok=True); os.makedirs(FIGS, exist_ok=True)\n",
    "FIRST, LAST = EPOCHS[0][\"id\"], EPOCHS[-1][\"id\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06249e00",
   "metadata": {},
   "source": [
    "## 3. Study area — Lagos State and LGAs (FAO GAUL 2015)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bec9f809",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "f_ng_lagos = ee.Filter.And(ee.Filter.eq(\"ADM0_NAME\", \"Nigeria\"), ee.Filter.eq(\"ADM1_NAME\", \"Lagos\"))\n",
    "state = ee.FeatureCollection(\"FAO/GAUL/2015/level1\").filter(f_ng_lagos)\n",
    "lgas = ee.FeatureCollection(\"FAO/GAUL/2015/level2\").filter(f_ng_lagos)\n",
    "assert state.size().getInfo() == 1, \"Lagos State not found in GAUL level1\"\n",
    "aoi = state.geometry()\n",
    "bbox = aoi.bounds()\n",
    "ring = bbox.coordinates().getInfo()[0]\n",
    "BOUNDS = [[min(p[1] for p in ring), min(p[0] for p in ring)], [max(p[1] for p in ring), max(p[0] for p in ring)]]\n",
    "LGAS = sorted(lgas.aggregate_array(\"ADM2_NAME\").getInfo())\n",
    "print(len(LGAS), \"LGAs:\", \", \".join(LGAS))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "656ab54e",
   "metadata": {},
   "source": [
    "## 4. Dynamic World land cover per epoch and a fixed land mask"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc8ab768",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def dw_label(year):\n",
    "    a, b = DW_WINDOWS[year]\n",
    "    return (ee.ImageCollection(\"GOOGLE/DYNAMICWORLD/V1\").filterBounds(aoi).filterDate(a, b)\n",
    "            .select(\"label\").reduce(ee.Reducer.mode()).toInt().rename(\"DW\").clip(aoi))\n",
    "\n",
    "DW = {y: dw_label(y) for y in OBS_YEARS}\n",
    "# Land = not water in ANY epoch (fixed mask so lagoon-edge changes don't move the denominator)\n",
    "LAND = ee.Image(1).clip(aoi)\n",
    "for y in DW:\n",
    "    LAND = LAND.And(DW[y].neq(0))\n",
    "LAND = LAND.rename(\"land\")\n",
    "\n",
    "def built_of(y): return DW[y].eq(6).rename(\"built\")\n",
    "def vegref_of(y): return DW[y].remap(VEG_REF, [1] * len(VEG_REF), 0).rename(\"veg\")\n",
    "\n",
    "lga_area = (ee.Image.pixelArea().divide(1e6).updateMask(LAND)\n",
    "            .reduceRegions(collection=lgas, reducer=ee.Reducer.sum(), scale=SCALE, tileScale=4)\n",
    "            .map(lambda f: ee.Feature(None, {\"lga\": f.get(\"ADM2_NAME\"), \"km2\": f.get(\"sum\")})).getInfo())\n",
    "LAND_KM2 = {f[\"properties\"][\"lga\"]: f[\"properties\"][\"km2\"] for f in lga_area[\"features\"]}\n",
    "print(\"Land area (km²):\", round(sum(LAND_KM2.values())))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28061a14",
   "metadata": {},
   "source": [
    "## 5. Landsat 8/9 C2 L2 → LST (°C), NDVI; one median composite per epoch\n",
    "`LST = ST_B10 × 0.00341802 + 149.0 − 273.15`; QA_PIXEL bits 0–4 (fill, dilated cloud, cirrus, cloud, shadow) masked.\n",
    "Landsat 9 data begin in early 2022, so 2019 is Landsat 8 only and 2021 is mostly Landsat 8."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9324a2a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def prep(img):\n",
    "    clear = img.select(\"QA_PIXEL\").bitwiseAnd(0b11111).eq(0)\n",
    "    lst = img.select(\"ST_B10\").multiply(0.00341802).add(149.0).subtract(273.15).rename(\"LST\")\n",
    "    sr = img.select([\"SR_B4\", \"SR_B5\"]).multiply(0.0000275).add(-0.2)\n",
    "    ndvi = sr.normalizedDifference([\"SR_B5\", \"SR_B4\"]).rename(\"NDVI\")\n",
    "    ok = lst.gte(LST_VALID_RANGE[0]).And(lst.lte(LST_VALID_RANGE[1]))\n",
    "    return lst.addBands(ndvi).updateMask(clear.And(ok)).copyProperties(img, [\"system:time_start\"])\n",
    "\n",
    "def landsat(cid, e):\n",
    "    return (ee.ImageCollection(cid).filterBounds(aoi).filterDate(e[\"start\"], e[\"end\"])\n",
    "            .filter(ee.Filter.lt(\"CLOUD_COVER\", MAX_SCENE_CLOUD)))\n",
    "\n",
    "stat = (ee.Reducer.mean().combine(ee.Reducer.stdDev(), sharedInputs=True)\n",
    "        .combine(ee.Reducer.count(), sharedInputs=True))\n",
    "RR = dict(geometry=aoi, scale=SCALE, maxPixels=1e10, tileScale=4)\n",
    "\n",
    "IM, E = {}, {}      # EE images and python results per epoch\n",
    "for e in EPOCHS:\n",
    "    c8, c9 = landsat(\"LANDSAT/LC08/C02/T1_L2\", e), landsat(\"LANDSAT/LC09/C02/T1_L2\", e)\n",
    "    n8, n9 = c8.size().getInfo(), c9.size().getInfo()\n",
    "    if n8 + n9 == 0:\n",
    "        raise RuntimeError(f\"{e['id']}: no Landsat scenes — widen the window or raise MAX_SCENE_CLOUD\")\n",
    "    col = c8.merge(c9).map(prep)\n",
    "    obs = col.select(\"LST\").count()\n",
    "    comp = col.median().updateMask(obs.gte(MIN_CLEAR_OBS)).clip(aoi)\n",
    "    lst = comp.select(\"LST\").updateMask(LAND)\n",
    "    ndvi = comp.select(\"NDVI\").updateMask(LAND)\n",
    "    built, veg = built_of(e[\"year\"]), vegref_of(e[\"year\"])\n",
    "\n",
    "    cov = lst.mask().gt(0).updateMask(LAND).reduceRegion(ee.Reducer.mean(), **RR).values().get(0).getInfo()\n",
    "    zone = built.add(veg.multiply(2)).selfMask().rename(\"zone\")\n",
    "    groups = lst.addBands(zone).reduceRegion(stat.group(groupField=1, groupName=\"zone\"), **RR).get(\"groups\").getInfo()\n",
    "    zd = {g[\"zone\"]: g for g in groups}\n",
    "    if 1 not in zd or 2 not in zd:\n",
    "        raise RuntimeError(f\"{e['id']}: no valid built-up or vegetated pixels — coverage {cov:.0%}\")\n",
    "    u, r = zd[1], zd[2]\n",
    "    IM[e[\"id\"]] = {\"lst\": lst, \"anom\": lst.subtract(r[\"mean\"]).rename(\"ANOM\"), \"ndvi\": ndvi, \"built\": built}\n",
    "    E[e[\"id\"]] = {**e, \"landsat8\": n8, \"landsat9\": n9, \"coverage\": round(cov, 3),\n",
    "                  \"urban_mean\": round(u[\"mean\"], 2), \"urban_std\": round(u[\"stdDev\"], 2),\n",
    "                  \"rural_mean\": round(r[\"mean\"], 2), \"rural_std\": round(r[\"stdDev\"], 2),\n",
    "                  \"suhi\": round(u[\"mean\"] - r[\"mean\"], 2)}\n",
    "    flag = \"  <-- LOW COVERAGE\" if cov < 0.5 else \"\"\n",
    "    print(f\"{e['id']} {e['label']:<20} L8={n8:<3} L9={n9:<3} coverage={cov:5.1%}  \"\n",
    "          f\"built={u['mean']:.2f}  veg={r['mean']:.2f}  SUHI={u['mean']-r['mean']:+.2f} °C{flag}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5465324a",
   "metadata": {},
   "source": [
    "## 6. Hotspot threshold (fixed from the 2019 baseline) and map display ranges"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11d6ec8f",
   "metadata": {},
   "outputs": [],
   "source": [
    "pb = (IM[FIRST][\"lst\"].addBands(IM[FIRST][\"anom\"])\n",
    "      .reduceRegion(ee.Reducer.percentile([2, HOTSPOT_PERCENTILE, 98]), **RR).getInfo())\n",
    "T_ANOM = pb[f\"ANOM_p{HOTSPOT_PERCENTILE}\"]\n",
    "LST_RANGE = [int(np.floor(pb[\"LST_p2\"])), int(np.ceil(pb[\"LST_p98\"]))]\n",
    "ANOM_RANGE = [int(np.floor(pb[\"ANOM_p2\"])), int(np.ceil(pb[\"ANOM_p98\"]))]\n",
    "print(f\"Hotspot = heat excess ≥ {T_ANOM:.2f} °C; LST display {LST_RANGE}; heat-excess display {ANOM_RANGE}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc7b044a",
   "metadata": {},
   "source": [
    "## 7. LGA statistics and hotspot area for every epoch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "db76da11",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "LS = {}   # LS[epoch_id][lga] = dict of stats\n",
    "for eid, im in IM.items():\n",
    "    valid = im[\"lst\"].mask().gt(0).updateMask(LAND).rename(\"coverage\")\n",
    "    hot = im[\"anom\"].gte(T_ANOM)\n",
    "    img = (im[\"lst\"].rename(\"lst_mean\").addBands(im[\"anom\"].rename(\"heat_excess\"))\n",
    "           .addBands(im[\"ndvi\"].rename(\"ndvi_mean\"))\n",
    "           .addBands(im[\"built\"].updateMask(LAND).rename(\"built_share\"))\n",
    "           .addBands(valid).addBands(hot.unmask(0).updateMask(im[\"lst\"].mask()).rename(\"hot_share\")))\n",
    "    fc = img.reduceRegions(collection=lgas, reducer=ee.Reducer.mean(), scale=SCALE, tileScale=4)\n",
    "    # select() keeps only properties that exist (an LGA with no valid pixels has no mean)\n",
    "    fc = fc.map(lambda f: f.select(\n",
    "        [\"ADM2_NAME\", \"lst_mean\", \"heat_excess\", \"ndvi_mean\", \"built_share\", \"coverage\", \"hot_share\"], None, False))\n",
    "    LS[eid] = {}\n",
    "    for f in fc.getInfo()[\"features\"]:\n",
    "        p = f[\"properties\"]\n",
    "        LS[eid][p.pop(\"ADM2_NAME\")] = {k: (None if p.get(k) is None else round(p[k], 4)) for k in\n",
    "                                       [\"lst_mean\", \"heat_excess\", \"ndvi_mean\", \"built_share\", \"coverage\", \"hot_share\"]}\n",
    "    km2 = (ee.Image.pixelArea().divide(1e6).updateMask(hot.selfMask())\n",
    "           .reduceRegion(ee.Reducer.sum(), **RR).values().get(0).getInfo())\n",
    "    E[eid][\"hot_km2\"] = round(km2 or 0, 1)\n",
    "    low = [l for l, s in LS[eid].items() if (s[\"coverage\"] or 0) < COVERAGE_MIN_LGA]\n",
    "    print(f\"{eid}: hotspot area {E[eid]['hot_km2']:.1f} km²; LGAs below coverage threshold: {low or 'none'}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b72eb8a1",
   "metadata": {},
   "source": [
    "## 8. Trend model and scenario projections (2027, 2029)\n",
    "\n",
    "**Panel:** LGA × observed year (2019, 2021, 2023, 2025): heat excess and built-up share.\n",
    "\n",
    "**Model (LGA fixed effects):** heat_excess(i,t) = α_i + β·built_share(i,t) + γ·year + ε\n",
    "- β = warming from built-up expansion (°C per unit built-up share)\n",
    "- γ = background drift not explained by expansion (densification, tree loss inside built areas, materials)\n",
    "\n",
    "**Scenarios** from each LGA's 2025 level:\n",
    "- **S1 — growth continues:** built-up share keeps growing at the LGA's own 2019–2025 linear rate → Δ = β·Δbuilt + γ·Δt\n",
    "- **S2 — no further growth:** built-up frozen at 2025 → Δ = γ·Δt (only the observed background drift)\n",
    "\n",
    "**Uncertainty:** 2,000 cluster-bootstrap draws (resampling LGAs) → 95% intervals.\n",
    "**Validation (hindcast):** fit on 2019–2023 only, predict 2025, compare with observed 2025 and a no-change baseline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab218952",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "# --- MODEL START ---\n",
    "def ok(s, cov_min=0.30):\n",
    "    return s is not None and s.get(\"heat_excess\") is not None and (s.get(\"coverage\") or 0) >= cov_min\n",
    "\n",
    "def make_rows(LS, years, cov_min=0.30):\n",
    "    \"\"\"Panel rows {lga, year, he, built} for LGA-years passing the coverage threshold. LS keyed by str(year).\"\"\"\n",
    "    rows = []\n",
    "    for y in years:\n",
    "        for lga, s in LS[str(y)].items():\n",
    "            if ok(s, cov_min):\n",
    "                rows.append({\"lga\": lga, \"year\": y, \"he\": s[\"heat_excess\"], \"built\": s[\"built_share\"]})\n",
    "    return rows\n",
    "\n",
    "def group(rows):\n",
    "    g = {}\n",
    "    for r in rows:\n",
    "        g.setdefault(r[\"lga\"], []).append(r)\n",
    "    return g\n",
    "\n",
    "def balanced(rows, n_years):\n",
    "    keep = {l for l, rs in group(rows).items() if len(rs) == n_years}\n",
    "    return [r for r in rows if r[\"lga\"] in keep], sorted(keep)\n",
    "\n",
    "def fit_fe(rows):\n",
    "    \"\"\"Within (fixed-effects) estimator. Returns (beta per unit built share, gamma per year).\"\"\"\n",
    "    X, Y = [], []\n",
    "    for rs in group(rows).values():\n",
    "        if len(rs) < 2:\n",
    "            continue\n",
    "        b = np.array([r[\"built\"] for r in rs]); t = np.array([r[\"year\"] for r in rs], float)\n",
    "        h = np.array([r[\"he\"] for r in rs])\n",
    "        X += list(zip(b - b.mean(), t - t.mean())); Y += list(h - h.mean())\n",
    "    coef, *_ = np.linalg.lstsq(np.array(X), np.array(Y), rcond=None)\n",
    "    return float(coef[0]), float(coef[1])\n",
    "\n",
    "def growth_rates(rows):\n",
    "    \"\"\"Per-LGA OLS slope of built-up share on year (share per year).\"\"\"\n",
    "    return {lga: float(np.polyfit([r[\"year\"] for r in rs], [r[\"built\"] for r in rs], 1)[0])\n",
    "            for lga, rs in group(rows).items() if len(rs) >= 2}\n",
    "\n",
    "def project(rows, beta, gamma, growth, base_year, years):\n",
    "    out = {}\n",
    "    for lga, rs in group(rows).items():\n",
    "        base = next((r for r in rs if r[\"year\"] == base_year), None)\n",
    "        if base is None or lga not in growth:\n",
    "            continue\n",
    "        out[lga] = {}\n",
    "        for Y in years:\n",
    "            d = Y - base_year\n",
    "            b_proj = min(1.0, max(0.0, base[\"built\"] + growth[lga] * d))\n",
    "            out[lga][Y] = {\"S1\": base[\"he\"] + beta * (b_proj - base[\"built\"]) + gamma * d,\n",
    "                           \"S2\": base[\"he\"] + gamma * d, \"built_S1\": b_proj}\n",
    "    return out\n",
    "\n",
    "def weighted(values, weights):\n",
    "    k = [l for l in values if l in weights]\n",
    "    w = np.array([weights[l] for l in k])\n",
    "    return float(np.dot([values[l] for l in k], w) / w.sum())\n",
    "\n",
    "def ci(a):\n",
    "    return [round(float(np.percentile(a, 2.5)), 2), round(float(np.percentile(a, 97.5)), 2)]\n",
    "\n",
    "def run_projection(LS, LAND_KM2, obs_years, proj_years, B=2000, seed=42, cov_min=0.30):\n",
    "    base_year = obs_years[-1]\n",
    "    rows, lgas_ok = balanced(make_rows(LS, obs_years, cov_min), len(obs_years))\n",
    "    beta, gamma = fit_fe(rows)\n",
    "    growth = growth_rates(rows)\n",
    "    point = project(rows, beta, gamma, growth, base_year, proj_years)\n",
    "\n",
    "    rng = np.random.default_rng(seed)\n",
    "    g = group(rows)\n",
    "    draws = {\"beta\": [], \"gamma\": [], \"agg\": {Y: {\"S1\": [], \"S2\": []} for Y in proj_years},\n",
    "             \"lga\": {l: {Y: {\"S1\": [], \"S2\": []} for Y in proj_years} for l in lgas_ok}}\n",
    "    for _ in range(B):\n",
    "        sample = rng.choice(lgas_ok, size=len(lgas_ok), replace=True)\n",
    "        boot = [{**r, \"lga\": f\"{l}#{k}\"} for k, l in enumerate(sample) for r in g[l]]\n",
    "        try:\n",
    "            b_, g_ = fit_fe(boot)\n",
    "        except np.linalg.LinAlgError:\n",
    "            continue\n",
    "        draws[\"beta\"].append(b_); draws[\"gamma\"].append(g_)\n",
    "        pr = project(rows, b_, g_, growth, base_year, proj_years)\n",
    "        for Y in proj_years:\n",
    "            for s in (\"S1\", \"S2\"):\n",
    "                draws[\"agg\"][Y][s].append(weighted({l: pr[l][Y][s] for l in pr}, LAND_KM2))\n",
    "                for l in pr:\n",
    "                    draws[\"lga\"][l][Y][s].append(pr[l][Y][s])\n",
    "\n",
    "    observed = [{\"year\": y, \"he\": round(weighted({r[\"lga\"]: r[\"he\"] for r in rows if r[\"year\"] == y}, LAND_KM2), 2)}\n",
    "                for y in obs_years]\n",
    "    base = {r[\"lga\"]: r for r in rows if r[\"year\"] == base_year}\n",
    "    return {\n",
    "        \"obs_years\": list(obs_years), \"base_year\": base_year, \"proj_years\": list(proj_years),\n",
    "        \"n_lgas\": len(lgas_ok), \"lgas\": lgas_ok, \"bootstrap_draws\": len(draws[\"beta\"]),\n",
    "        \"beta_per_10pp\": round(beta * 0.1, 3), \"beta_per_10pp_ci\": [round(v * 0.1, 3) for v in ci(draws[\"beta\"])],\n",
    "        \"gamma_per_yr\": round(gamma, 3), \"gamma_per_yr_ci\": ci(draws[\"gamma\"]),\n",
    "        \"aggregate\": {\"observed\": observed,\n",
    "                      **{s: [{\"year\": Y, \"he\": round(weighted({l: point[l][Y][s] for l in point}, LAND_KM2), 2),\n",
    "                              \"ci\": ci(draws[\"agg\"][Y][s])} for Y in proj_years] for s in (\"S1\", \"S2\")}},\n",
    "        \"lga\": {l: {\"he_base\": round(base[l][\"he\"], 2), \"built_base\": round(base[l][\"built\"], 4),\n",
    "                    \"growth_pp_per_yr\": round(growth[l] * 100, 2),\n",
    "                    **{str(Y): {\"S1\": round(point[l][Y][\"S1\"], 2), \"S1_ci\": ci(draws[\"lga\"][l][Y][\"S1\"]),\n",
    "                                \"S2\": round(point[l][Y][\"S2\"], 2), \"S2_ci\": ci(draws[\"lga\"][l][Y][\"S2\"]),\n",
    "                                \"built_S1\": round(point[l][Y][\"built_S1\"], 4)} for Y in proj_years}}\n",
    "                for l in point},\n",
    "    }\n",
    "\n",
    "def hindcast(LS, LAND_KM2, obs_years, cov_min=0.30):\n",
    "    \"\"\"Fit on all but the last observed epoch, predict the last one; compare with a no-change baseline.\"\"\"\n",
    "    train_years, target = obs_years[:-1], obs_years[-1]\n",
    "    rows, lgas_ok = balanced(make_rows(LS, obs_years, cov_min), len(obs_years))\n",
    "    train = [r for r in rows if r[\"year\"] in train_years]\n",
    "    beta, gamma = fit_fe(train)\n",
    "    growth = growth_rates(train)\n",
    "    last = {r[\"lga\"]: r for r in train if r[\"year\"] == train_years[-1]}\n",
    "    obs = {r[\"lga\"]: r for r in rows if r[\"year\"] == target}\n",
    "    d = target - train_years[-1]\n",
    "    pred_model = {l: last[l][\"he\"] + beta * growth[l] * d + gamma * d for l in lgas_ok}\n",
    "    pred_naive = {l: last[l][\"he\"] for l in lgas_ok}\n",
    "    def metrics(p):\n",
    "        e = np.array([p[l] - obs[l][\"he\"] for l in lgas_ok])\n",
    "        return {\"mae\": round(float(np.abs(e).mean()), 2), \"bias\": round(float(e.mean()), 2),\n",
    "                \"aggregate_error\": round(weighted(p, LAND_KM2) - weighted({l: obs[l][\"he\"] for l in lgas_ok}, LAND_KM2), 2)}\n",
    "    return {\"n_lgas\": len(lgas_ok), \"trained_on\": list(train_years), \"predicted\": target,\n",
    "            \"model\": metrics(pred_model), \"no_change_baseline\": metrics(pred_naive)}\n",
    "# --- MODEL END ---\n",
    "\n",
    "PROJ = run_projection(LS, LAND_KM2, OBS_YEARS, PROJECTION_YEARS, B=BOOTSTRAP_N, seed=SEED, cov_min=COVERAGE_MIN_LGA)\n",
    "HIND = hindcast(LS, LAND_KM2, OBS_YEARS, cov_min=COVERAGE_MIN_LGA)\n",
    "print(f\"LGAs in balanced panel: {PROJ['n_lgas']}\")\n",
    "print(f\"β = {PROJ['beta_per_10pp']:+.3f} °C per +10 pp built-up  (95% CI {PROJ['beta_per_10pp_ci']})\")\n",
    "print(f\"γ = {PROJ['gamma_per_yr']:+.3f} °C/yr background drift   (95% CI {PROJ['gamma_per_yr_ci']})\")\n",
    "for k, v in PROJ[\"aggregate\"].items():\n",
    "    print(k, v)\n",
    "print(\"Hindcast:\", json.dumps(HIND, indent=1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4192a0c2",
   "metadata": {},
   "source": [
    "## 9. Web-map overlays (PNG)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b912c07",
   "metadata": {},
   "outputs": [],
   "source": [
    "def save_thumb(img, name):\n",
    "    url = img.getThumbURL({\"region\": bbox, \"dimensions\": PNG_DIMENSIONS, \"format\": \"png\", \"crs\": \"EPSG:4326\"})\n",
    "    resp = requests.get(url, timeout=300); resp.raise_for_status()\n",
    "    open(f\"{DATA}/{name}\", \"wb\").write(resp.content)\n",
    "    print(\"saved\", name, f\"{len(resp.content)/1e6:.1f} MB\")\n",
    "\n",
    "for eid in IM:\n",
    "    save_thumb(IM[eid][\"lst\"].visualize(min=LST_RANGE[0], max=LST_RANGE[1], palette=PAL_LST), f\"lst_{eid}.png\")\n",
    "    save_thumb(IM[eid][\"anom\"].visualize(min=ANOM_RANGE[0], max=ANOM_RANGE[1], palette=PAL_LST), f\"excess_{eid}.png\")\n",
    "\n",
    "save_thumb(IM[LAST][\"anom\"].subtract(IM[FIRST][\"anom\"]).visualize(min=-4, max=4, palette=PAL_DIV), \"change.png\")\n",
    "# Hotspot persistence: 1 = hot in baseline only (cooled), 2 = new by latest, 3 = hot in both\n",
    "hA, hB = IM[FIRST][\"anom\"].gte(T_ANOM), IM[LAST][\"anom\"].gte(T_ANOM)\n",
    "persist = hA.add(hB.multiply(2)).selfMask().updateMask(IM[FIRST][\"lst\"].mask().And(IM[LAST][\"lst\"].mask()))\n",
    "save_thumb(persist.visualize(min=1, max=3, palette=[\"4575b4\", \"fdae61\", \"a50026\"]), \"hotspots_change.png\")\n",
    "save_thumb(built_of(int(LAST)).And(built_of(int(FIRST)).Not()).selfMask().visualize(palette=[\"6a3d9a\"]), \"new_built.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "415c8a12",
   "metadata": {},
   "source": [
    "## 10. Save data for the web map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38a21d2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "lga_geo = lgas.map(lambda f: ee.Feature(f.geometry().simplify(100), {\"lga\": f.get(\"ADM2_NAME\")})).getInfo()\n",
    "for f in lga_geo[\"features\"]:\n",
    "    f[\"properties\"][\"land_km2\"] = round(LAND_KM2.get(f[\"properties\"][\"lga\"], 0), 1)\n",
    "json.dump({\"type\": \"FeatureCollection\", \"features\": lga_geo[\"features\"]}, open(f\"{DATA}/lga.geojson\", \"w\"))\n",
    "\n",
    "panel = [{\"epoch\": eid, \"lga\": l, **s} for eid in LS for l, s in LS[eid].items()]\n",
    "json.dump(panel, open(f\"{DATA}/lga_panel.json\", \"w\"))\n",
    "json.dump({**PROJ, \"hindcast\": HIND}, open(f\"{DATA}/projections.json\", \"w\"), indent=1)\n",
    "\n",
    "summary = {\n",
    "    \"title\": f\"Lagos Urban Heat Island {OBS_YEARS[0]}–{OBS_YEARS[-1]}\",\n",
    "    \"generated_utc\": dt.datetime.now(dt.timezone.utc).strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\n",
    "    \"epochs\": [E[e[\"id\"]] for e in EPOCHS], \"first\": FIRST, \"last\": LAST,\n",
    "    \"hotspot\": {\"definition\": f\"heat excess ≥ {FIRST} p{HOTSPOT_PERCENTILE}\", \"threshold_c\": round(T_ANOM, 2)},\n",
    "    \"lst_range\": LST_RANGE, \"excess_range\": ANOM_RANGE, \"change_range\": [-4, 4],\n",
    "    \"pal_lst\": PAL_LST, \"pal_div\": PAL_DIV, \"coverage_min_lga\": COVERAGE_MIN_LGA,\n",
    "    \"bounds\": BOUNDS, \"synthetic\": False,\n",
    "}\n",
    "json.dump(summary, open(f\"{DATA}/summary.json\", \"w\"), indent=2)\n",
    "print(json.dumps(summary[\"epochs\"], indent=1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bab5d490",
   "metadata": {},
   "source": [
    "## 11. README figures"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2fb84431",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.rcParams.update({\"figure.dpi\": 150, \"font.size\": 9})\n",
    "agg = PROJ[\"aggregate\"]; P_LAST = str(PROJECTION_YEARS[-1])\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(6.5, 3.6))\n",
    "oy = [o[\"year\"] for o in agg[\"observed\"]]; oh = [o[\"he\"] for o in agg[\"observed\"]]\n",
    "ax.plot(oy, oh, \"-o\", c=\"k\", label=\"Observed\")\n",
    "for s, c, lab in ((\"S1\", \"#d73027\", \"S1 growth continues\"), (\"S2\", \"#4575b4\", \"S2 no further growth\")):\n",
    "    ys = [BASE_YEAR] + [p[\"year\"] for p in agg[s]]; hs = [oh[-1]] + [p[\"he\"] for p in agg[s]]\n",
    "    lo = [oh[-1]] + [p[\"ci\"][0] for p in agg[s]]; hi = [oh[-1]] + [p[\"ci\"][1] for p in agg[s]]\n",
    "    ax.plot(ys, hs, \"--o\", c=c, label=lab); ax.fill_between(ys, lo, hi, color=c, alpha=0.15)\n",
    "ax.set_ylabel(\"Mean heat excess (°C)\"); ax.set_xticks(OBS_YEARS + PROJECTION_YEARS)\n",
    "ax.set_title(\"Lagos-wide surface heat excess: observed and projected\"); ax.legend(fontsize=8); fig.tight_layout()\n",
    "fig.savefig(f\"{FIGS}/trend_projection.png\")\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(6, 3.2))\n",
    "ax.bar([E[e[\"id\"]][\"label\"] for e in EPOCHS], [E[e[\"id\"]][\"suhi\"] for e in EPOCHS], color=\"#d73027\")\n",
    "ax.set_ylabel(\"SUHI intensity (°C)\\nbuilt-up − vegetated\")\n",
    "ax.set_title(\"Surface UHI intensity by epoch\"); fig.tight_layout(); fig.savefig(f\"{FIGS}/suhi_by_epoch.png\")\n",
    "\n",
    "lg = sorted(PROJ[\"lga\"].items(), key=lambda kv: kv[1][P_LAST][\"S1\"])\n",
    "fig, ax = plt.subplots(figsize=(6.5, 5.5)); yy = np.arange(len(lg))\n",
    "ax.barh(yy - 0.27, [v[\"he_base\"] for _, v in lg], 0.27, color=\"#999\", label=f\"{BASE_YEAR} observed\")\n",
    "ax.barh(yy, [v[P_LAST][\"S2\"] for _, v in lg], 0.27, color=\"#4575b4\", label=f\"{P_LAST} S2 no growth\")\n",
    "ax.barh(yy + 0.27, [v[P_LAST][\"S1\"] for _, v in lg], 0.27, color=\"#d73027\", label=f\"{P_LAST} S1 growth continues\")\n",
    "ax.set_yticks(yy, [k for k, _ in lg]); ax.set_xlabel(\"Heat excess (°C)\"); ax.legend(fontsize=7, loc=\"lower right\")\n",
    "ax.set_title(f\"LGA heat excess: {BASE_YEAR} and {P_LAST} scenarios\"); fig.tight_layout()\n",
    "fig.savefig(f\"{FIGS}/lga_projection.png\")\n",
    "\n",
    "bl = sorted(LGAS, key=lambda l: (LS[LAST][l][\"built_share\"] or 0))\n",
    "fig, ax = plt.subplots(figsize=(6.5, 5)); yy = np.arange(len(bl))\n",
    "ax.barh(yy - 0.2, [(LS[FIRST][l][\"built_share\"] or 0) * 100 for l in bl], 0.4, color=\"#bbb\", label=FIRST)\n",
    "ax.barh(yy + 0.2, [(LS[LAST][l][\"built_share\"] or 0) * 100 for l in bl], 0.4, color=\"#6a3d9a\", label=LAST)\n",
    "ax.set_yticks(yy, bl); ax.set_xlabel(\"Built-up share of land (%) — Dynamic World\"); ax.legend()\n",
    "ax.set_title(f\"Built-up expansion by LGA, {FIRST} → {LAST}\"); fig.tight_layout(); fig.savefig(f\"{FIGS}/built_by_lga.png\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5693def",
   "metadata": {},
   "source": [
    "## 12. Package outputs and download"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "722d1b3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "shutil.make_archive(\"uhi_outputs\", \"zip\", OUT)\n",
    "try:\n",
    "    from google.colab import drive, files\n",
    "    drive.mount(\"/content/drive\")\n",
    "    dest = \"/content/drive/MyDrive/urban-heat-island-lagos\"\n",
    "    os.makedirs(dest, exist_ok=True)\n",
    "    shutil.copy(\"uhi_outputs.zip\", dest)\n",
    "    for n in (\"summary.json\", \"projections.json\"):\n",
    "        shutil.copy(f\"{DATA}/{n}\", dest)\n",
    "    print(\"Saved to Google Drive:\", dest)\n",
    "    files.download(\"uhi_outputs.zip\")\n",
    "except ImportError:\n",
    "    print(\"Zip written to\", os.path.abspath(\"uhi_outputs.zip\"))\n",
    "print(\"ALL DONE\")"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "formats": "ipynb,py:percent",
   "main_language": "python"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
