Source code: Car-park occupancy from Sentinel-1 radar in Python: Walmart store closures as a natural experiment

Runnable Python scripts, requirements and console output for the tutorial “Car-park occupancy from Sentinel-1 radar in Python: Walmart store closures as…

Last updated

These are the exact scripts used to produce every figure and number in Car-park occupancy from Sentinel-1 radar in Python: Walmart store closures as a natural experiment. Download them, install the requirements into a fresh virtual environment and run them from this folder.

Written and tested by

Run it
python -m venv .venv
.venv\Scripts\activate # macOS/Linux: source .venv/bin/activate
pip install -r requirements.txt
python car_park_radar.py

car_park_radar.py

car_park_radar.py
"""Car-park occupancy from space: Walmart car parks in Chicagoland with Sentinel-1 radar and NAIP aerial imagery.
Sentinel-1's 10 m pixels cannot see individual cars, but a car park full of metal boxes scatters more radar
energy back to the satellite than an empty sheet of asphalt. This script tests whether that aggregate signal
is strong enough to see, using the cleanest natural experiment available: Walmart closed three Supercenters in
Chicagoland in spring 2023 (Homewood and Plainfield on 10 March, Chicago Chatham by 16 April). It:
1. finds Walmart Supercenters in Overture Maps places and their buildings, and draws each car park as the
ring around the store minus roads and neighbouring buildings,
2. keeps only paved ground in that ring using NAIP 4-band aerial imagery (NDVI and colour saturation),
3. reads every Sentinel-1 radiometrically terrain-corrected (RTC) ascending pass over each car park from
2017 to now from the Microsoft Planetary Computer,
4. compares each closed store against the open stores imaged on the same pass (a difference-in-differences),
with every open store run through the same test as a placebo,
5. shows a closure in NAIP imagery from before and after.
Plainfield sits at the edge of the regular ascending track, so it has too few passes and the script says so.
No API keys are needed. Run with: python car_park_radar.py
"""
import os
import platform
import time
from concurrent.futures import ThreadPoolExecutor
from importlib.metadata import version
from pathlib import Path
os.environ.update(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR", GDAL_HTTP_MERGE_CONSECUTIVE_RANGES="YES",
GDAL_HTTP_MAX_RETRY="5", GDAL_HTTP_RETRY_DELAY="3")
import duckdb
import geopandas as gpd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import planetary_computer
import pystac_client
import rasterio
import shapely
from rasterio.features import geometry_mask, shapes, sieve
from rasterio.windows import from_bounds
from scipy import stats
HERE = Path(__file__).parent
OUT, DATA = HERE / "output", HERE / "data"
for d in (OUT, DATA / "s1"):
d.mkdir(parents=True, exist_ok=True)
plt.rcParams.update({"figure.dpi": 150, "savefig.bbox": "tight", "font.size": 9})
pd.set_option("display.width", 160)
print("=== versions ===")
print(f"python {platform.python_version()} | rasterio {rasterio.__version__} | geopandas {gpd.__version__} | "
f"shapely {shapely.__version__} | pystac-client {version('pystac-client')} | duckdb {duckdb.__version__} | "
f"numpy {np.__version__} | pandas {pd.__version__}")
def section(title: str) -> None:
print(f"\n=== {title} ===")
BBOX = (-88.32, 41.50, -87.52, 42.08) # lon/lat: Chicago, the south suburbs and the I-55/I-88 corridor
CRS = "EPSG:32616" # UTM zone 16N, metres
REL = "2026-11-18.0" # Overture Maps release
END = "2026-11-18" # last Sentinel-1 date to read
# The three Chicagoland Supercenters Walmart closed in 2023: store location and the date it closed to the public.
# Homewood and Plainfield: Walmart statement reported by Supermarket News, 13 February 2023.
# Chatham: Walmart, "Walmart Announces Closure of Four Chicago Stores", 11 April 2023.
CLOSED = {
"Homewood, 17550 S Halsted St": (41.56759, -87.63689, "2023-03-10"),
"Plainfield, 12690 S Route 59": (41.65376, -88.20637, "2023-03-10"),
"Chicago Chatham, 8331 S Stewart Ave": (41.74026, -87.63301, "2023-04-16"),
}
ROAD_W = {"motorway": 16, "trunk": 14, "primary": 12, "secondary": 10, "tertiary": 9, "residential": 7,
"unclassified": 7, "living_street": 6}
# --- Step 1: stores and car parks from Overture Maps ----------------------------------------------
section("Step 1: Walmart Supercenters and their car parks from Overture Maps")
con = duckdb.connect()
con.sql("INSTALL spatial; LOAD spatial; INSTALL httpfs; LOAD httpfs; SET s3_region = 'us-west-2';")
coll = con.sql(f"SELECT collection, bbox, assets.aws.alternate.s3.href AS href FROM "
f"read_parquet('https://stac.overturemaps.org/{REL}/collections.parquet')").df()
def overture(collection: str, cols: str, box: tuple, where: str = "TRUE") -> gpd.GeoDataFrame:
"""Rows from one Overture collection inside a lon/lat box, reading only the files that overlap it."""
x0, y0, x1, y1 = box
files = [r.href for r in coll[coll.collection == collection].itertuples()
if r.bbox["xmin"] <= x1 and r.bbox["xmax"] >= x0 and r.bbox["ymin"] <= y1 and r.bbox["ymax"] >= y0]
bb = f"bbox.xmin <= {x1} AND bbox.xmax >= {x0} AND bbox.ymin <= {y1} AND bbox.ymax >= {y0}"
df = con.sql(f"SELECT {cols}, ST_AsWKB(geometry) AS wkb FROM read_parquet({files}) WHERE {bb} AND {where}").df()
return gpd.GeoDataFrame(df.drop(columns="wkb"), geometry=shapely.from_wkb(df.wkb.apply(bytes)), crs=4326)
places_file = DATA / "walmart_places.parquet"
if not places_file.exists():
overture("place", "id, names.primary AS name, basic_category AS category", BBOX,
"names.primary ILIKE 'walmart%'").to_parquet(places_file)
places = gpd.read_parquet(places_file)
print(f"{len(places)} Overture places whose name starts with Walmart; top categories: "
f"{places.category.value_counts().head(5).to_dict()}")
# drop the in-store services (pharmacy, fuel, vision centre and so on); the building test below does the rest
SERVICES = r"pharmacy|fuel|gas|vision|auto|tire|photo|bakery|deli|money|pickup|garden|neighborhood|optical|liquor"
cand = places[~places.name.str.lower().str.contains(SERVICES)].to_crs(CRS).reset_index(drop=True)
# one point per store: Overture often has two or three listings for the same shop
keep, taken = [], np.zeros(len(cand), bool)
xy = np.c_[cand.geometry.x, cand.geometry.y]
for i in range(len(cand)):
if not taken[i]:
taken |= np.hypot(*(xy - xy[i]).T) < 250
keep.append(i)
opened = cand.iloc[keep][["geometry"]].reset_index(drop=True)
closed_pts = gpd.GeoSeries(gpd.points_from_xy([v[1] for v in CLOSED.values()], [v[0] for v in CLOSED.values()]),
crs=4326).to_crs(CRS)
opened = opened[[closed_pts.distance(p).min() > 400 for p in opened.geometry]] # stale listings of the closures
opened["name"] = [f"open {i + 1}" for i in range(len(opened))]
opened["closed"] = pd.NaT
closed = gpd.GeoDataFrame({"name": list(CLOSED), "closed": pd.to_datetime([v[2] for v in CLOSED.values()])},
geometry=closed_pts.values, crs=CRS)
stores = gpd.GeoDataFrame(pd.concat([closed, opened], ignore_index=True), crs=CRS)
print(f"{len(opened)} open Walmart store points after merging duplicate listings, plus {len(CLOSED)} closed stores")
def car_park(p: shapely.Point) -> dict | None:
"""Store footprint at the place point and the car park around it, all in CRS metres."""
box = tuple(gpd.GeoSeries([p.buffer(450)], crs=CRS).to_crs(4326).total_bounds)
f = DATA / f"ctx_{p.x:.0f}_{p.y:.0f}.parquet"
if not f.exists():
b = overture("building", "'building' AS kind, NULL AS class", box)
s = overture("segment", "'road' AS kind, class", box, "subtype = 'road'")
pd.concat([b, s], ignore_index=True).to_parquet(f)
ctx = gpd.read_parquet(f).to_crs(CRS)
B = ctx[(ctx.kind == "building") & ctx.geom_type.isin(["Polygon", "MultiPolygon"])]
big = B[(B.area > 6000) & (B.distance(p) < 120)]
if big.empty:
return None
i = big.distance(p).idxmin() # the building at the place point, not a larger neighbour
fp = big.loc[i].geometry
others = B.drop(index=i)
R = ctx[(ctx.kind == "road") & ctx["class"].isin(ROAD_W)]
lot = fp.buffer(110).difference(fp.buffer(8))
lot = lot.difference(shapely.union_all(others.geometry.buffer(3).values))
lot = lot.difference(shapely.union_all([g.buffer(ROAD_W[c] / 2 + 2) for g, c in zip(R.geometry, R["class"])]))
parts = [q for q in getattr(lot, "geoms", [lot]) if q.distance(fp) < 30 and q.area > 2000]
return {"footprint": fp, "roof": fp.buffer(-15), "lot": shapely.union_all(parts)} if parts else None
geo = [car_park(p) for p in stores.geometry]
for k in ("footprint", "roof", "lot"):
stores[k] = [g[k] if g else None for g in geo]
stores = stores[stores.footprint.notna()]
stores = stores[stores.footprint.apply(lambda g: g.area) > 9000].reset_index(drop=True) # Supercenter-sized
print(f"{len(stores)} stores with a Supercenter-sized building (over 9,000 m2) at the listed point, "
f"{stores.closed.notna().sum()} of them closed")
# --- Step 2: keep only paved ground, using NAIP --------------------------------------------------
section("Step 2: paved-surface masks from NAIP aerial imagery")
cat = pystac_client.Client.open("https://planetarycomputer.microsoft.com/api/stac/v1",
modifier=planetary_computer.sign_inplace)
RES = 2.0 # resample NAIP's 0.6 m pixels to 2 m: plenty for a car-park mask
def to_ll(geom: shapely.Geometry) -> shapely.Geometry:
return gpd.GeoSeries([geom], crs=CRS).to_crs(4326).iloc[0]
def naip_items(geom_ll: shapely.Geometry) -> list:
"""NAIP scenes from 2017 to 2023 over a lon/lat geometry, oldest first, preferring scenes that cover all of it."""
items = cat.search(collections=["naip"], intersects=geom_ll.centroid, datetime="2017-01-01/2023-12-31").items()
items = [i for i in items if "image" in i.assets]
whole = [i for i in items if shapely.geometry.shape(i.geometry).contains(geom_ll)]
return sorted(whole or items, key=lambda i: i.datetime)
def read_naip(item, geom: shapely.Geometry, pad: float = 0.0, res: float = RES):
"""4-band NAIP (R, G, B, NIR) resampled to `res` metres over the bounds of a CRS geometry."""
with rasterio.open(item.assets["image"].href) as src:
g = gpd.GeoSeries([geom], crs=CRS).to_crs(src.crs).iloc[0]
x0, y0, x1, y1 = g.buffer(pad).bounds
h, w = int((y1 - y0) / res), int((x1 - x0) / res)
a = src.read([1, 2, 3, 4], window=from_bounds(x0, y0, x1, y1, src.transform), out_shape=(4, h, w),
boundless=True, fill_value=0).astype("f4")
return a, rasterio.transform.from_bounds(x0, y0, x1, y1, w, h), src.crs
def paved(lot: shapely.Geometry) -> tuple:
item = naip_items(to_ll(lot))[-1]
a, tr, crs = read_naip(item, lot)
ndvi = (a[3] - a[0]) / np.maximum(a[3] + a[0], 1)
sat = (a[:3].max(0) - a[:3].min(0)) / np.maximum(a[:3].max(0), 1) # asphalt and concrete are grey; soil is tan
m = sieve(((ndvi < 0.10) & (sat < 0.20) & (a[0] > 0)).astype("uint8"), size=int(60 / RES ** 2))
pv = shapely.union_all([shapely.geometry.shape(g) for g, v in shapes(m, mask=m == 1, transform=tr)])
pv = gpd.GeoSeries([pv], crs=crs).to_crs(CRS).iloc[0]
new = lot.intersection(pv).buffer(-1).buffer(1)
new = shapely.union_all([q for q in getattr(new, "geoms", [new]) if q.area > 400])
return new, item.datetime.date()
with ThreadPoolExecutor(8) as ex:
res = list(ex.map(paved, stores.lot))
stores["paved_frac"] = [r[0].area / lot.area for r, lot in zip(res, stores.lot)]
stores["lot"] = [r[0] for r in res]
stores["naip_date"] = [r[1] for r in res]
stores["lot_m2"] = stores.lot.apply(lambda g: g.area)
stores = stores[stores.lot_m2 > 12000].reset_index(drop=True)
print(f"{len(stores)} stores keep more than 12,000 m2 of paved car park; median {stores.lot_m2.median():,.0f} m2, "
f"median paved share of the ring {stores.paved_frac.median():.2f}")
print(stores[stores.closed.notna()][["name", "lot_m2", "paved_frac", "naip_date"]].round(2).to_string(index=False))
# --- Step 3: Sentinel-1 RTC backscatter over every car park ----------------------------------------
section("Step 3: Sentinel-1 RTC gamma0 over each car park and roof, every ascending pass since 2017")
def read_pass(item, name: str, zones: dict) -> dict:
"""Mean VV and VH gamma0 (linear) over the car park and the roof for one Sentinel-1 RTC item."""
rec = {"name": name, "t": item.datetime, "orbit": item.properties["sat:relative_orbit"],
"platform": item.properties.get("platform")}
for pol in ("vv", "vh"):
if pol not in item.assets:
continue
for attempt in range(4):
try:
with rasterio.open(planetary_computer.sign(item.assets[pol].href)) as src:
z = {k: gpd.GeoSeries([g], crs=CRS).to_crs(src.crs).iloc[0] for k, g in zones.items()}
x0, y0, x1, y1 = z["lot"].union(z["roof"]).bounds
w = from_bounds(x0 - 20, y0 - 20, x1 + 20, y1 + 20, src.transform).round_offsets().round_lengths()
arr = src.read(1, window=w, boundless=True, fill_value=0).astype("f8")
tr = src.window_transform(w)
break
except rasterio.errors.RasterioIOError:
if attempt == 3:
raise
time.sleep(3 + 5 * attempt)
for k, g in z.items():
v = arr[geometry_mask([g], out_shape=arr.shape, transform=tr, invert=True) & (arr > 0)]
rec[f"{pol}_{k}"] = v.mean() if v.size else np.nan
return rec
def series(row, pool) -> pd.DataFrame:
f = DATA / "s1" / f"{row.name.split(',')[0].replace(' ', '_')}.parquet"
if f.exists():
return pd.read_parquet(f)
items = [i for i in cat.search(collections=["sentinel-1-rtc"], intersects=to_ll(row.lot.centroid),
datetime=f"2017-01-01/{END}").items()
if i.properties["sat:orbit_state"] == "ascending"]
zones = {"lot": row.lot, "roof": row.roof}
df = pd.DataFrame(list(pool.map(lambda it: read_pass(it, row.name, zones), items))).sort_values("t")
df.to_parquet(f)
return df
t0 = time.time()
with ThreadPoolExecutor(32) as pool:
S = pd.concat([series(r, pool) for r in stores.itertuples()], ignore_index=True)
for c in ("vv_lot", "vv_roof", "vh_lot", "vh_roof"):
S[c.replace("_", "_db_")] = 10 * np.log10(S[c])
S["date"] = S.t.dt.tz_convert(None).dt.normalize()
S = S.dropna(subset=["vv_db_lot"]).reset_index(drop=True)
print(f"{len(S):,} store-passes read in {time.time() - t0:.0f} s; dates per ascending orbit: "
f"{S.groupby('orbit').date.nunique().to_dict()}; usual local time of the pass: "
f"{S.t.dt.tz_convert('America/Chicago').dt.strftime('%H:%M').str[:4].mode().iloc[0]}0")
# --- Step 4: difference-in-differences against the open stores on the same pass -------------------
section("Step 4: did the car parks go quiet when the stores closed?")
# On a single pass every store sees the same weather, the same satellite and the same season, so the difference
# between one car park and the median of the other open car parks on that pass cancels most of what is not cars.
open_names = set(stores.loc[stores.closed.isna(), "name"])
n_open = S[S.name.isin(open_names)].groupby(["orbit", "date"]).size().rename("n_open")
S = S.join(n_open, on=["orbit", "date"])
S = S[S.n_open >= 5].reset_index(drop=True)
def relative(name: str) -> pd.DataFrame:
"""One store's car park minus the median of the other open car parks on the same pass, in dB."""
s = S[S.name == name]
ctrl = S[S.name.isin(open_names - {name})].groupby(["orbit", "date"]).vv_db_lot.median()
return s.assign(rel=s.vv_db_lot.values - ctrl.reindex(pd.MultiIndex.from_frame(s[["orbit", "date"]])).values)
def step(rel: pd.DataFrame, when: pd.Timestamp) -> tuple:
"""Mean relative backscatter from 30 days to two years after a date, minus the two years before."""
d = (rel.date - when).dt.days
before, after = rel.rel[(d >= -730) & (d < -30)].dropna(), rel.rel[(d > 30) & (d <= 730)].dropna()
return after.mean() - before.mean(), stats.ttest_ind(after, before, equal_var=False).pvalue, len(before), len(after)
rows = []
for r in stores.itertuples():
rel = relative(r.name)
dates = [r.closed] if pd.notna(r.closed) else [pd.Timestamp("2023-03-10"), pd.Timestamp("2023-04-16")]
for when in dates:
dd, p, nb, na = step(rel, when)
rows.append({"store": r.name, "group": "open" if pd.isna(r.closed) else "closed", "date": when.date(),
"step_db": dd, "p": p, "passes_before": nb, "passes_after": na})
R = pd.DataFrame(rows)
thin = R[(R.passes_before < 20) | (R.passes_after < 20)]
gone = thin.drop_duplicates("store")
print(f"left out: {len(gone)} stores ({(gone.group == 'closed').sum()} closed: "
f"{', '.join(gone[gone.group == 'closed'].store)}) with fewer than 20 comparable passes on one side of the "
f"date; they lie at the edge of the regular ascending track")
R = R.drop(thin.index)
closed_steps = R[R.group == "closed"]
placebo = R[R.group == "open"].groupby("store").step_db.mean()
print(closed_steps.round({"step_db": 2}).to_string(index=False, formatters={"p": "{:.1e}".format}))
print(f"\nopen stores run through the same test (placebo), n = {len(placebo)}: mean {placebo.mean():+.2f} dB, "
f"sd {placebo.std():.2f} dB, range {placebo.min():+.2f} to {placebo.max():+.2f} dB")
z = (closed_steps.step_db.mean() - placebo.mean()) / placebo.std()
below = [(placebo <= s).mean() for s in closed_steps.step_db]
print(f"closed stores: mean step {closed_steps.step_db.mean():+.2f} dB, {z:+.1f} placebo standard deviations; "
f"share of open stores with a step as low as each closed store: {np.round(below, 3).tolist()}")
R.to_csv(OUT / "closure_steps.csv", index=False)
# --- Step 5: figures ------------------------------------------------------------------------------
section("Step 5: figures")
ATTR = ("Contains modified Copernicus Sentinel data, RTC processed by Microsoft Planetary Computer | "
"Stores: Overture Maps Foundation, © OpenStreetMap contributors | NAIP: USDA Farm Production and Conservation")
colours = dict(zip(CLOSED, ["#d32f2f", "#ef6c00", "#6a1b9a"]))
stores_ix = stores.set_index("name")
def rgb_of(a: np.ndarray) -> np.ndarray:
return np.clip(a[:3].transpose(1, 2, 0) / np.percentile(a[:3][a[:3] > 0], 99.5), 0, 1)
# 5a. the car-park masks on NAIP for one closed and one open store
example_open = stores_ix.loc[placebo.index].paved_frac.idxmax() # the open store with the cleanest paved ring
fig, axes = plt.subplots(1, 2, figsize=(10, 5.2))
for ax, name in zip(axes, ["Homewood, 17550 S Halsted St", example_open]):
r = stores_ix.loc[name]
item = naip_items(to_ll(r.lot))[-1]
a, tr, crs = read_naip(item, r.lot, pad=40, res=1.0)
rgb = rgb_of(a)
ax.imshow(rgb, extent=(tr.c, tr.c + tr.a * rgb.shape[1], tr.f + tr.e * rgb.shape[0], tr.f))
gpd.GeoSeries([r.lot], crs=CRS).to_crs(crs).boundary.plot(ax=ax, color="#ffd600", lw=0.9)
gpd.GeoSeries([r.roof], crs=CRS).to_crs(crs).boundary.plot(ax=ax, color="#00e5ff", lw=0.9, ls="--")
label = f"Walmart {name}" if pd.notna(r.closed) else "An open Chicagoland Supercenter"
ax.set_title(f"{label}, NAIP {item.datetime:%B %Y}\ncar park (yellow, {r.lot_m2:,.0f} m²) and roof sample (cyan)",
fontsize=8)
ax.set_axis_off()
fig.text(0.01, 0.01, ATTR, fontsize=5)
fig.savefig(OUT / "car_park_masks_naip.png"); plt.close(fig)
# 5b. relative backscatter through the closures, 90-day rolling mean
fig, ax = plt.subplots(figsize=(9, 4.2))
for name in closed_steps.store:
c = colours[name]
rel = relative(name).set_index("date").rel.dropna().sort_index()
ax.plot(rel.index, rel.rolling("90D").mean(), color=c, lw=1.4, label=name)
ax.axvline(pd.Timestamp(CLOSED[name][2]), color=c, lw=0.8, ls=":")
op = pd.concat([relative(n) for n in placebo.index]).groupby("date").rel.median().dropna().sort_index()
ax.plot(op.index, op.rolling("90D").mean(), color="#0071ce", lw=1.2, label="median open Supercenter (each against the others)")
ax.axhline(0, color="k", lw=0.5)
ax.set_ylabel("car park VV minus the open car parks\non the same pass, dB (90-day mean)")
ax.set_title("Chicagoland Walmart car parks seen by Sentinel-1; dotted lines mark the 2023 closures")
ax.legend(fontsize=7, loc="lower left")
fig.text(0.01, -0.03, ATTR, fontsize=5)
fig.savefig(OUT / "closure_time_series.png"); plt.close(fig)
# 5c. the closure step against the placebo distribution
fig, ax = plt.subplots(figsize=(7.5, 3.4))
lo = min(placebo.min(), closed_steps.step_db.min()) - 0.2
ax.hist(placebo, bins=np.arange(np.floor(lo * 5) / 5, placebo.max() + 0.3, 0.1), color="#90caf9", edgecolor="white",
label=f"open Supercenters, same test (n = {len(placebo)})")
for r in closed_steps.itertuples():
ax.axvline(r.step_db, color=colours[r.store], lw=2, label=f"{r.store.split(',')[0]} ({r.step_db:+.2f} dB)")
ax.set_xlabel("car-park backscatter relative to open stores: two years after minus two years before, dB")
ax.set_ylabel("stores")
ax.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(integer=True))
ax.set_title("Closed stores against the placebo distribution")
ax.legend(fontsize=7, loc="upper left")
fig.savefig(OUT / "closure_step_vs_placebo.png"); plt.close(fig)
# 5d. NAIP before and after one closure
r = stores_ix.loc["Homewood, 17550 S Halsted St"]
items = naip_items(to_ll(r.lot))
pre = [i for i in items if i.datetime.date() < r.closed.date()][-1]
post = [i for i in items if i.datetime.date() > r.closed.date()][-1]
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
for ax, it in zip(axes, (pre, post)):
a, tr, crs = read_naip(it, r.lot, pad=20, res=0.6)
ax.imshow(rgb_of(a))
ax.set_title(f"NAIP {it.datetime:%d %B %Y}", fontsize=9)
ax.set_axis_off()
fig.suptitle(f"Walmart Homewood, 17550 S Halsted St: before and after it closed on {r.closed:%d %B %Y}", fontsize=10)
fig.text(0.01, 0.01, "NAIP: USDA Farm Production and Conservation, via Microsoft Planetary Computer", fontsize=6)
fig.savefig(OUT / "naip_before_after.png"); plt.close(fig)
print("saved: car_park_masks_naip.png, closure_time_series.png, closure_step_vs_placebo.png, naip_before_after.png")