Lesson 2 · 10:45–11:30

Why are some places cooler?

What covers the ground decides its surface temperature.
Tree cover (canopy) comes from Meta and WRI's tree-height map: an AI model estimated the height of every ~1 m spot from Maxar satellite photos taken mostly in 2018–2020, and we count the share of each square under trees taller than 3 m. Buildings and roads (built) and water come from ESA's WorldCover map, which sorts every 10 m cell into trees, crops, buildings, water and so on from 2021 Sentinel-1 radar and Sentinel-2 photos. Each 240 m square is the average of its 8 × 8 squares of 30 m. See it, get it. Meta's tree-height viewer shows the whole world, and the files are on AWS Open Data: the one file under Bengaluru is 477 MB, so we read it once and keep only the tree share per 30 m square (6 MB). The WorldCover viewer shows the world at 10 m; Bengaluru's 3° × 3° tile is 128 MB. Download the 240 m table:
px = datapack.table("pixels")  # the city in 240 m squares
px[["ward", "lst_day", "canopy", "built", "water"]].head()  # lst_day = surface temperature at 10:40 am, °C
ward lst_day canopy built water
North 3 · Chowdeshwari ward 36.8 0.19 0 0
North 3 · Chowdeshwari ward 35.3 0.17 0 0
North 3 · Chowdeshwari ward 39 0.1 0.01 0
North 3 · Chowdeshwari ward 35.3 0.22 0 0
North 3 · Chowdeshwari ward 32.3 0.02 0 0.02

More trees, cooler ground

Each dot is a square (across: tree cover, up: surface temperature at 10:40 am). Drag a box to see where they are.
How this file was made · making it reads Meta and WRI's ~1 m tree-height map over the whole city, about 3 minutes

The chart reads a small prepared file (6.4 MB): your copy in data/ if you have one, otherwise it downloads once. To make it yourself from the original data, run uv run wardheat datapack build --step canopy --step features --force. This is the code that runs:

def step_canopy(force=False):
    from . import landcover
    from .grid import block_mean

    if datapack.exists("canopy_frac") and not force:
        return
    g10, g30 = city_grid(10), city_grid(30)
    _log(f"canopy: streaming Meta canopy-height v1 tiles {landcover.chm_tiles()}")
    last = {"t": 0}

    def prog(ti, nt, rs, r1):
        if time.time() - last["t"] > 30:
            _log(f"  canopy tile {ti+1}/{nt} row {rs}/{r1}")
            last["t"] = time.time()

    f10 = landcover.canopy_fraction(g10, progress=prog)
    save_geotiff(_out("canopy_frac"), block_mean(f10, 3)[: g30.height, : g30.width], g30)
    _log(f"canopy: done, city canopy {np.nanmean(f10)*100:.1f}%")


def canopy_fraction(grid: Grid, version: str = "v1", threshold_m: float = 3.0, agg: int = 8, strip: int = 2048, progress=None) -> np.ndarray:
    """Fraction of each ``grid`` pixel covered by tree canopy taller than ``threshold_m``.

    Streams each canopy-height tile in horizontal strips, thresholds at 1.2 m,
    averages ``agg x agg`` blocks (~9.6 m) in Web Mercator, and finally
    reprojects the fractions to ``grid`` with area-weighted averaging.
    """
    spec = CHM[version]
    tile_size = 2 * _WEB_MERC_HALF / 2 ** spec["zoom"]
    px = tile_size / spec["tile_px"]
    cres = px * agg
    b = transform_bounds(grid.crs, "EPSG:3857", *grid.bounds)
    # mosaic lattice snapped to the global CHM pixel lattice
    left = -_WEB_MERC_HALF + math.floor((b[0] + _WEB_MERC_HALF) / cres) * cres
    top = _WEB_MERC_HALF - math.floor((_WEB_MERC_HALF - b[3]) / cres) * cres
    W = int(math.ceil((b[2] - left) / cres))
    H = int(math.ceil((top - b[1]) / cres))
    mosaic = np.full((H, W), np.nan, dtype="float32")
    mtr = Affine(cres, 0, left, 0, -cres, top)
    tiles = chm_tiles(version=version)
    with rasterio.Env(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR", GDAL_HTTP_MAX_RETRY="3", GDAL_CACHEMAX=512):
        for ti, qk in enumerate(tiles):
            with rasterio.open(chm_url(qk, version)) as src:
                ib = (max(b[0], src.bounds.left), max(b[1], src.bounds.bottom), min(b[2], src.bounds.right), min(b[3], src.bounds.top))
                if ib[0] >= ib[2] or ib[1] >= ib[3]:
                    continue
                win = outer_window(from_bounds(*ib, src.transform))
                # align window to agg-pixel blocks of the global lattice
                c0 = (int(win.col_off) // agg) * agg
                r0 = (int(win.row_off) // agg) * agg
                c1 = min(src.width, int(math.ceil((win.col_off + win.width) / agg)) * agg)
                r1 = min(src.height, int(math.ceil((win.row_off + win.height) / agg)) * agg)
                for rs in range(r0, r1, strip):
                    re_ = min(r1, rs + strip)
                    a = src.read(1, window=((rs, re_), (c0, c1)))
                    m = (a >= threshold_m).astype("float32")
                    if spec["nodata"] is not None:
                        m[a == spec["nodata"]] = np.nan
                    frac = block_mean(m, agg)
                    # place into mosaic
                    x_left = src.transform.c + c0 * px
                    y_top = src.transform.f - rs * px
                    mc = int(round((x_left - left) / cres))
                    mr = int(round((top - y_top) / cres))
                    hh, ww = frac.shape
                    rr0, cc0 = max(mr, 0), max(mc, 0)
                    rr1, cc1 = min(mr + hh, H), min(mc + ww, W)
                    if rr1 > rr0 and cc1 > cc0:
                        mosaic[rr0:rr1, cc0:cc1] = frac[rr0 - mr : rr1 - mr, cc0 - mc : cc1 - mc]
                    if progress:
                        progress(ti, len(tiles), rs, r1)
    return reproject_array(mosaic, mtr, "EPSG:3857", grid, resampling=Resampling.average)
Shade and evaporating water lower the surface temperature; bare soil and dark roofs raise it.

How much cooler?

built = px[px.built > 0.5]  # squares more than half buildings and roads

# fit a straight line: surface temperature = slope × canopy + intercept
slope, intercept = np.polyfit(built.canopy, built.lst_day, deg=1)
Every extra 10 % of tree cover ≈ 0.7 °C lower surface temperature (7,967 squares more than half built-up).

Day and night

Farmland has the highest surface temperature by day and is cool at night; built-up squares stay warm after dark: the urban heat island. At night MODIS sees 1 km blocks, so a park takes on the warmth of the streets around it; only the farmland-versus-city gap is clear.

Try it

  1. Box the coolest dots at the bottom: which lakes? 2. Box hot squares with no trees: which wards? 3. Densest squares only:
dense = px[px.built > 0.8]  # change the threshold here
dense_slope, _ = np.polyfit(dense.canopy, dense.lst_day, deg=1)
f"{len(dense):,} dense squares: about {-dense_slope * 0.1:.1f} °C lower surface temperature per 10 % more canopy"

5,045 dense squares: about 0.8 °C lower surface temperature per 10 % more canopy

Made with open data and open-source Python · marimo · Altair