Source code: GIS retail site selection in Python: drive-time catchments, suitability scoring and the Huff model

Runnable Python scripts, requirements and console output for the tutorial “GIS retail site selection in Python: drive-time catchments, suitability…

Last updated

These are the exact scripts used to produce every figure and number in GIS retail site selection in Python: drive-time catchments, suitability scoring and the Huff model. 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 site_selection.py

site_selection.py

site_selection.py
"""GIS retail site selection in Python: drive-time catchments, a suitability score and a Huff gravity model.
Builds a drivable road network for metro Albuquerque from Overture Maps transportation segments, spreads
American Community Survey (ACS 2019-2023) households and income onto it, finds the large grocery and
general-merchandise stores from Overture places and buildings, and then:
1. measures 5, 10 and 15-minute drive-time catchments,
2. scores candidate sites on arterial roads with a transparent weighted overlay (households, spending power,
gap to the nearest competitor, road access) and checks the demand criteria against where Walmart trades,
3. runs a Huff gravity model to estimate the spending each candidate would capture from the competition,
4. replays the 2022 network with Walmart's San Mateo Boulevard store (closed March 2023) to see how it ranked.
No API keys are needed. Run with: python site_selection.py
"""
import platform
import re
from importlib.metadata import version
from pathlib import Path
import contextily as cx
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 requests
import shapely
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components, dijkstra
from scipy.spatial import cKDTree
HERE = Path(__file__).parent
OUT, DATA = HERE / "output", HERE / "data"
for d in (OUT, DATA):
d.mkdir(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()} | duckdb {duckdb.__version__} | geopandas {gpd.__version__} | "
f"shapely {shapely.__version__} | scipy {version('scipy')} | numpy {np.__version__} | pandas {pd.__version__}")
def section(title: str) -> None:
print(f"\n=== {title} ===")
BBOX = (-106.82, 34.96, -106.45, 35.30) # lon/lat: Albuquerque, Rio Rancho and the edge of Los Lunas
CRS = "EPSG:32613" # UTM zone 13N, metres
REL = "2026-11-18.0" # Overture Maps release
UA = {"User-Agent": "technicalgis-tutorial (https://technicalgis.com)"}
# --- Step 1: households and income from the ACS -----------------------------------------------
section("Step 1: census tracts, households and income (ACS 2019-2023)")
tracts_file = DATA / "tracts_nm_2023.gpkg"
if not tracts_file.exists():
r = requests.get("https://www2.census.gov/geo/tiger/TIGER2023/TRACT/tl_2023_35_tract.zip", headers=UA, timeout=300)
r.raise_for_status()
(DATA / "tl_2023_35_tract.zip").write_bytes(r.content)
gpd.read_file(DATA / "tl_2023_35_tract.zip").to_file(tracts_file)
tracts = gpd.read_file(tracts_file, bbox=BBOX).to_crs(CRS)
tracts = tracts[tracts.ALAND > 0].reset_index(drop=True)
def acs_table(table: str) -> pd.DataFrame:
"""One ACS 5-year detailed table for every geography, from the key-free table-based summary file."""
f = DATA / f"acsdt5y2023-{table}.dat"
if not f.exists():
url = f"https://www2.census.gov/programs-surveys/acs/summary_file/2023/table-based-SF/data/5YRData/{f.name}"
r = requests.get(url, headers=UA, timeout=600)
r.raise_for_status()
f.write_bytes(r.content)
t = pd.read_csv(f, sep="|", dtype={"GEO_ID": str}, low_memory=False)
return t[t.GEO_ID.str.startswith("1400000US35")].set_index("GEO_ID")
acs = pd.DataFrame({
"households": acs_table("b11001")["B11001_E001"],
"population": acs_table("b01003")["B01003_E001"],
"median_income": acs_table("b19013")["B19013_E001"],
})
acs.index = acs.index.str[-11:]
acs["median_income"] = acs.median_income.where(acs.median_income > 0) # suppressed tracts carry negative codes
tracts = tracts.merge(acs, left_on="GEOID", right_index=True, how="left")
tracts[["households", "population"]] = tracts[["households", "population"]].fillna(0)
tracts["median_income"] = tracts.median_income.fillna(tracts.median_income.median())
tracts["spend"] = tracts.households * tracts.median_income # aggregate household income: a spending proxy
print(f"{len(tracts)} tracts | {tracts.population.sum():,.0f} people | {tracts.households.sum():,.0f} households | "
f"median of tract median incomes ${tracts.median_income.median():,.0f}")
# --- Step 2: a drivable network from Overture transportation segments ---------------------------
section("Step 2: road network 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, where: str = "TRUE") -> pd.DataFrame:
"""Rows from one Overture collection inside BBOX, reading only the files whose extent overlaps it."""
x0, y0, x1, y1 = BBOX
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}"
return con.sql(f"SELECT {cols}, ST_AsWKB(geometry) AS wkb FROM read_parquet({files}) WHERE {bb} AND {where}").df()
def to_gdf(df: pd.DataFrame) -> gpd.GeoDataFrame:
g = gpd.GeoDataFrame(df.drop(columns="wkb"), geometry=shapely.from_wkb(df.wkb.apply(bytes)), crs=4326)
return g.to_crs(CRS)
SPEED = {"motorway": 100, "trunk": 75, "primary": 60, "secondary": 55, "tertiary": 45, "unclassified": 40,
"residential": 35, "living_street": 15, "service": 20} # km/h, typical urban running speeds
seg_file = DATA / "overture_segments.parquet"
if not seg_file.exists():
classes = ", ".join(f"'{c}'" for c in SPEED)
overture("segment", "id, class AS cls, connectors", f"subtype = 'road' AND class IN ({classes})").to_parquet(seg_file)
seg = to_gdf(pd.read_parquet(seg_file))
seg["length_m"] = seg.length
# Overture connectors mark where segments join, at a fraction 'at' along each segment: split each
# segment at its connectors and each piece becomes one edge of the graph.
cid, xs, ys, edges = {}, [], [], []
for s in seg.itertuples():
ids = []
for c in sorted(s.connectors, key=lambda c: c["at"]):
if c["connector_id"] not in cid:
p = s.geometry.interpolate(c["at"], normalized=True)
cid[c["connector_id"]] = len(xs); xs.append(p.x); ys.append(p.y)
ids.append((cid[c["connector_id"]], c["at"]))
for (a, ta), (b, tb) in zip(ids, ids[1:]):
if a != b:
edges.append((a, b, s.length_m * (tb - ta) / (SPEED[s.cls] / 3.6) / 60, s.cls))
nodes = np.c_[xs, ys]
E = pd.DataFrame(edges, columns=["a", "b", "minutes", "cls"])
n = len(nodes)
W = coo_matrix((np.r_[E.minutes, E.minutes] + 1e-6, (np.r_[E.a, E.b], np.r_[E.b, E.a])), shape=(n, n)).tocsr()
_, comp = connected_components(W, directed=False)
main = comp == np.bincount(comp).argmax()
print(f"{len(seg):,} road segments -> {n:,} junctions and {len(E):,} edges; "
f"the largest connected network holds {main.mean():.1%} of junctions")
rank = {c: i for i, c in enumerate(SPEED)}
best_rank = np.full(n, len(SPEED) - 1)
for col in ("a", "b"): # each junction takes the most important class of road that touches it
np.minimum.at(best_rank, E[col].to_numpy(), E.cls.map(rank).to_numpy())
node_cls = np.array(list(SPEED))[best_rank]
main_idx = np.flatnonzero(main)
tree = cKDTree(nodes[main])
def snap(xy: np.ndarray) -> np.ndarray:
return main_idx[tree.query(xy)[1]]
# --- Step 3: spread households onto the network ---------------------------------------------------
section("Step 3: demand on the network")
resid = main & np.isin(node_cls, ["residential", "living_street", "unclassified", "tertiary"])
pts = gpd.GeoDataFrame({"node": np.flatnonzero(resid)},
geometry=gpd.points_from_xy(nodes[resid, 0], nodes[resid, 1]), crs=CRS)
j = gpd.sjoin(pts, tracts[["GEOID", "geometry"]], predicate="within")
groups = j.groupby("GEOID").node.apply(np.array)
demand_hh, demand_spend = np.zeros(n), np.zeros(n)
for t in tracts.itertuples():
ids = groups.get(t.GEOID)
if ids is None: # a tract with no residential street: its centroid's nearest junction
ids = snap(np.array([[t.geometry.centroid.x, t.geometry.centroid.y]]))
np.add.at(demand_hh, ids, t.households / len(ids))
np.add.at(demand_spend, ids, t.spend / len(ids))
print(f"{demand_hh.sum():,.0f} households placed on {np.count_nonzero(demand_hh):,} junctions "
f"({demand_hh.sum() / tracts.households.sum():.1%} of the tracts' total)")
# --- Step 4: the competition --------------------------------------------------------------------
section("Step 4: large grocery and general-merchandise stores")
CHAINS = {"Walmart": r"walmart", "Target": r"target", "Costco": r"costco", "Sam's Club": r"sam'?s club",
"Smith's": r"smith'?s", "Albertsons": r"albertsons", "Sprouts": r"sprouts", "Whole Foods": r"whole foods",
"Trader Joe's": r"trader joe'?s", "Natural Grocers": r"natural grocers"}
# In-store counters and services are listed as separate places: keep the store itself.
SERVICE = (r"pharmacy|vision|glasses|optical|bakery|deli\b|fuel|gas\b|money|pickup|delivery|garden|patio|tire|"
r"auto|photo|business center|charging|atm\b|liquor|portrait|#|\d{3,}")
pl_file = DATA / "overture_places.parquet"
if not pl_file.exists():
pat = ("^(" + "|".join(CHAINS.values()) + r")\b").replace("'", "''")
overture("place", "id, names.primary AS name, basic_category AS category, confidence",
f"regexp_matches(lower(names.primary), '{pat}')").to_parquet(pl_file)
places = to_gdf(pd.read_parquet(pl_file))
low = places.name.str.lower()
places["chain"] = [next((k for k, p in CHAINS.items() if re.match(rf"^{p}\b", nm)), None) for nm in low]
places = places[places.chain.notna() & ~low.str.contains(SERVICE) & (places.confidence > 0.5)]
bld_file = DATA / "overture_buildings_large.parquet"
if not bld_file.exists(): # the bounding-box test keeps only buildings that could exceed about 1,500 m2
overture("building", "id", "(bbox.xmax - bbox.xmin) * (bbox.ymax - bbox.ymin) > 1.5e-7").to_parquet(bld_file)
bld = to_gdf(pd.read_parquet(bld_file))
bld = bld[bld.area > 1500][["geometry"]].reset_index(drop=True)
bld["floor_m2"] = bld.area
# Attractiveness = the floor area of the store's building: the building under (or within 60 m of) each place.
# A place with no large building beneath it is a stale or misplaced listing (in this release, a vacant lot and
# two points with no store), so the inner join drops it.
n_places = places.chain.size
places = gpd.sjoin_nearest(places, bld, max_distance=60, how="inner")
stores = (places.sort_values("confidence", ascending=False)
.drop_duplicates("index_right") # one store per building, whichever listing is most confident
.drop(columns="index_right").reset_index(drop=True))
stores = stores[stores.floor_m2 > 2500].reset_index(drop=True)
# Walmart's San Mateo Boulevard SE store closed on 10 March 2023 (KRQE); Overture still lists it, so drop it
# from today's network and keep it for the 2022 replay in Step 8.
SAN_MATEO = gpd.GeoSeries(gpd.points_from_xy([-106.58773], [35.07626]), crs=4326).to_crs(CRS).iloc[0]
sm_floor = float(bld[bld.contains(SAN_MATEO)].floor_m2.max())
stores = stores[stores.distance(SAN_MATEO) > 150].reset_index(drop=True)
stores["fmt"] = np.where(stores.chain != "Walmart", stores.chain,
np.where(stores.floor_m2 > 9000, "Walmart Supercenter", "Walmart Neighborhood Market"))
print(f"{n_places} chain listings -> {len(stores)} stores with a building of more than 2,500 m2")
print(stores.groupby("fmt").agg(stores=("id", "size"), median_floor_m2=("floor_m2", "median")).round(0).to_string())
print(f"San Mateo Blvd SE (closed 2023): building {sm_floor:,.0f} m2")
# --- Step 5: drive-time catchments ---------------------------------------------------------------
section("Step 5: drive-time catchments")
store_node = snap(np.c_[stores.geometry.x, stores.geometry.y])
T_store = dijkstra(W, indices=store_node, limit=30) # minutes from every store to every junction, up to 30
wm = stores[stores.fmt == "Walmart Supercenter"].reset_index(drop=True)
wm_nodes = store_node[stores.fmt == "Walmart Supercenter"]
centre = gpd.GeoSeries(gpd.points_from_xy([-106.6504], [35.0844]), crs=4326).to_crs(CRS).get_coordinates().to_numpy()
ex = int(np.argmin(np.hypot(*(np.c_[wm.geometry.x, wm.geometry.y] - centre).T))) # the Supercenter nearest downtown
example = wm_nodes[ex]
T_ex = dijkstra(W, indices=[example], limit=20)[0]
ex_ll = gpd.GeoSeries([wm.geometry[ex]], crs=CRS).to_crs(4326).iloc[0]
for m in (5, 10, 15):
print(f"{m:2d}-minute catchment of the Supercenter at {ex_ll.y:.4f}, {ex_ll.x:.4f}: "
f"{demand_hh[T_ex <= m].sum():8,.0f} households")
art = main & np.isin(node_cls, ["trunk", "primary", "secondary"])
cell = np.floor(nodes / 500).astype(int) # one candidate per 500 m grid cell on an arterial road
cand = (pd.DataFrame({"node": np.flatnonzero(art), "cx": cell[art, 0], "cy": cell[art, 1]})
.drop_duplicates(["cx", "cy"]).node.to_numpy())
urban = tracts[tracts.households / (tracts.ALAND / 1e6) > 50].union_all() # built-up tracts only
cand = cand[shapely.contains_xy(urban, nodes[cand, 0], nodes[cand, 1])]
print(f"{len(cand):,} candidate sites (one per 500 m cell on trunk, primary and secondary roads in built-up tracts)")
# --- Step 6: suitability score -----------------------------------------------------------------
section("Step 6: weighted-overlay suitability")
LAMBDA, CATCH = 2.0, 10.0 # Huff distance-decay exponent; catchment for the overlay, minutes
def decay(t: np.ndarray) -> np.ndarray:
return np.where(np.isfinite(t), 1.0 / (1.0 + t) ** LAMBDA, 0.0)
A_new = float(wm.floor_m2.median()) # a typical Supercenter's floor area
S_now = (stores.floor_m2.to_numpy()[:, None] * decay(T_store)).sum(axis=0) # sum of A_k f(T_ik) at every junction
nearest_store = np.where(np.isfinite(T_store), T_store, 30).min(axis=0)
def batch_metrics(src: np.ndarray, S: np.ndarray) -> pd.DataFrame:
"""Households and spending inside CATCH minutes, and Huff-captured spending, for each source junction."""
rows = []
for k in range(0, len(src), 200):
T = dijkstra(W, indices=src[k:k + 200], limit=30)
a = A_new * decay(T)
rows.append(pd.DataFrame({"hh10": (demand_hh * (T <= CATCH)).sum(1),
"spend10": (demand_spend * (T <= CATCH)).sum(1),
"huff": (demand_spend * a / (S + a + 1e-12)).sum(1)}))
return pd.concat(rows, ignore_index=True)
C = batch_metrics(cand, S_now)
C["node"], C["x"], C["y"] = cand, nodes[cand, 0], nodes[cand, 1]
C["gap"] = nearest_store[cand] # minutes to the nearest existing large store
C["access"] = pd.Series(node_cls[cand]).map({"trunk": 1.0, "primary": 1.0, "secondary": 0.7}).to_numpy()
WEIGHTS = {"hh10": 0.35, "spend10": 0.25, "gap": 0.25, "access": 0.15}
for k in WEIGHTS:
C[f"r_{k}"] = C[k].rank(pct=True)
C["score"] = sum(w * C[f"r_{k}"] for k, w in WEIGHTS.items())
print(C[["hh10", "spend10", "gap", "access", "huff", "score"]].describe().T[["mean", "min", "50%", "max"]]
.round(2).to_string())
# Does the demand side of the score pick out places where Walmart already trades? Rank the existing
# Supercenters among the candidates on the two criteria that do not depend on the stores themselves.
M = batch_metrics(wm_nodes, S_now)
both = pd.concat([C[["hh10", "spend10"]], M[["hh10", "spend10"]]], ignore_index=True)
ds = 0.35 * both.hh10.rank(pct=True) + 0.25 * both.spend10.rank(pct=True)
pct = ds.rank(pct=True).iloc[len(C):].to_numpy()
print(f"existing Supercenters on households and spending within 10 minutes: median percentile {np.median(pct):.0%} "
f"(range {pct.min():.0%}-{pct.max():.0%}, {np.mean(pct > 0.5):.0%} in the top half)")
# --- Step 7: Huff gravity model ------------------------------------------------------------------
section("Step 7: Huff model - spending a new Supercenter would capture")
picks = []
for r in C.sort_values("huff", ascending=False).itertuples(): # the top sites, at least 3 km apart
if all(np.hypot(r.x - p.x, r.y - p.y) > 3000 for p in picks):
picks.append(r)
if len(picks) == 5:
break
P = pd.DataFrame(picks)
ll = gpd.GeoSeries(gpd.points_from_xy(P.x, P.y), crs=CRS).to_crs(4326)
P["lat"], P["lon"] = ll.y.round(4), ll.x.round(4)
tot = demand_spend.sum()
P["share"] = P.huff / tot
print(P[["lat", "lon", "hh10", "gap", "score", "huff", "share"]]
.assign(huff=lambda d: (d.huff / 1e6).round(0)).rename(columns={"huff": "huff_$m", "share": "share_of_metro"})
.round(3).to_string(index=False))
print(f"metro aggregate household income ${tot / 1e9:,.1f}bn | correlation between overlay score and Huff capture "
f"across candidates: {C.score.corr(C.huff):.2f}")
# --- Step 8: the 2022 network, with San Mateo Blvd SE still open -----------------------------------
section("Step 8: replaying 2022 with the San Mateo store")
st22 = pd.concat([stores, gpd.GeoDataFrame({"name": ["Walmart (San Mateo Blvd SE, closed 2023)"], "chain": ["Walmart"],
"fmt": ["Walmart Supercenter"], "floor_m2": [sm_floor]}, geometry=[SAN_MATEO], crs=CRS)],
ignore_index=True)
sm_node = snap(np.array([[SAN_MATEO.x, SAN_MATEO.y]]))
T22 = np.vstack([T_store, dijkstra(W, indices=sm_node, limit=30)])
F = st22.floor_m2.to_numpy()[:, None] * decay(T22)
share = F / (F.sum(axis=0) + 1e-12)
st22["huff_$m"] = (share * demand_spend).sum(axis=1) / 1e6
st22["per_m2"] = st22["huff_$m"] * 1e6 / st22.floor_m2
st22["hh10"] = (demand_hh * (T22 <= CATCH)).sum(axis=1)
st22["inc10"] = (demand_spend * (T22 <= CATCH)).sum(axis=1) / np.maximum(st22.hh10, 1)
w22 = st22[st22.fmt == "Walmart Supercenter"].sort_values("per_m2", ascending=False).reset_index(drop=True)
lo = gpd.GeoSeries(w22.geometry, crs=CRS).to_crs(4326)
w22["where"] = [f"{y:.3f}, {x:.3f}" for x, y in zip(lo.x, lo.y)]
print(w22[["where", "name", "floor_m2", "hh10", "inc10", "huff_$m", "per_m2"]].round(1).to_string())
sm = int(w22.index[w22.name.str.contains("San Mateo")][0])
print(f"San Mateo ranked {sm + 1} of {len(w22)} Supercenters on modelled spending per m2 of store")
# --- Step 9: figures -------------------------------------------------------------------------------
section("Step 9: figures")
COLORS = {"Walmart Supercenter": "#0071ce", "Walmart Neighborhood Market": "#79b8f0", "Target": "#cc0000",
"Smith's": "#ff9800", "Albertsons": "#7b1fa2", "Costco": "#2e7d32", "Sam's Club": "#00897b",
"Sprouts": "#9e9d24", "Whole Foods": "#455a64", "Trader Joe's": "#8d6e63", "Natural Grocers": "#c2185b"}
ATTR = ("Stores and roads: Overture Maps Foundation, © OpenStreetMap contributors | Households: US Census Bureau "
"ACS 2019-2023 | Basemap: Esri, HERE, Garmin, © OpenStreetMap contributors")
VIEW = gpd.GeoSeries([shapely.box(*BBOX)], crs=4326).to_crs(CRS).total_bounds
def basemap(ax):
ax.set_xlim(VIEW[0], VIEW[2]); ax.set_ylim(VIEW[1], VIEW[3])
cx.add_basemap(ax, crs=CRS, source=cx.providers.Esri.WorldGrayCanvas, zoom=11, attribution=ATTR, attribution_size=5)
ax.set_axis_off()
tracts["hh_km2"] = tracts.households / (tracts.ALAND / 1e6)
fig, ax = plt.subplots(figsize=(7.5, 7.5))
tracts.plot("hh_km2", ax=ax, cmap="YlOrBr", vmax=tracts.hh_km2.quantile(0.97), alpha=0.7, legend=True,
legend_kwds={"label": "households per km²", "shrink": 0.6})
for f, g in stores.groupby("fmt"):
g.plot(ax=ax, color=COLORS.get(f, "k"), markersize=np.sqrt(g.floor_m2) / 2.5, edgecolor="white",
linewidth=0.5, label=f, zorder=3)
ax.plot(SAN_MATEO.x, SAN_MATEO.y, "x", color="#d32f2f", ms=9, mew=2.2, label="Walmart San Mateo Blvd SE (closed 2023)", zorder=4)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, 0.0), ncol=3, fontsize=6.5, frameon=False)
ax.set_title("Metro Albuquerque: household density and the large grocery and general-merchandise stores")
basemap(ax)
fig.savefig(OUT / "demand_and_stores.png"); plt.close(fig)
fig, ax = plt.subplots(figsize=(7.5, 7))
m = main & (T_ex <= 15)
sc = ax.scatter(nodes[m, 0], nodes[m, 1], c=T_ex[m], s=1.0, cmap="viridis_r", vmin=0, vmax=15)
for mm in (5, 10, 15):
hull = shapely.concave_hull(shapely.MultiPoint(nodes[main & (T_ex <= mm)]), ratio=0.15)
gpd.GeoSeries([hull], crs=CRS).boundary.plot(ax=ax, color="k", lw=0.8)
ax.plot(*nodes[example], "*", color="#0071ce", ms=16, mec="white")
plt.colorbar(sc, ax=ax, shrink=0.6, label="drive time, minutes")
ax.set_title(f"5, 10 and 15-minute drive times from one Supercenter: "
f"{demand_hh[T_ex <= 10].sum():,.0f} households within 10 minutes")
basemap(ax)
fig.savefig(OUT / "drive_time_catchments.png"); plt.close(fig)
fig, axes = plt.subplots(1, 2, figsize=(11, 6.2))
for ax, col, title, cmap in ((axes[0], "score", "Weighted-overlay suitability (0 to 1)", "magma"),
(axes[1], "huff", "Huff model: spending a new Supercenter\nwould capture, $m a year", "viridis")):
v = C[col] / (1e6 if col == "huff" else 1)
sc = ax.scatter(C.x, C.y, c=v, s=8, cmap=cmap, edgecolor="none", zorder=2)
plt.colorbar(sc, ax=ax, shrink=0.7, orientation="horizontal", pad=0.02)
wm.plot(ax=ax, color="#0071ce", marker="s", markersize=26, edgecolor="white", label="Walmart Supercenter", zorder=3)
ax.set_title(title, fontsize=9)
basemap(ax)
axes[1].scatter(P.x, P.y, s=170, facecolor="none", edgecolor="red", lw=2, label="top five sites, 3 km apart", zorder=4)
for i, r in enumerate(P.itertuples(), 1):
axes[1].annotate(str(i), (r.x, r.y), xytext=(7, 7), textcoords="offset points", color="red", weight="bold")
axes[1].legend(loc="lower right", bbox_to_anchor=(1.0, 0.06), fontsize=7)
fig.savefig(OUT / "suitability_and_huff.png"); plt.close(fig)
fig, ax = plt.subplots(figsize=(7, 0.32 * len(w22) + 1.2))
ax.barh(w22["where"], w22.per_m2, color=["#d32f2f" if "San Mateo" in nm else "#0071ce" for nm in w22.name])
ax.invert_yaxis()
ax.set_xlabel("modelled household spending captured per m² of store, $ a year (Huff model, 2022 network)")
ax.set_ylabel("Supercenter (lat, lon)")
ax.set_title("Walmart Supercenters in metro Albuquerque in 2022; San Mateo Blvd SE in red")
fig.savefig(OUT / "huff_2022_supercenters.png"); plt.close(fig)
C.drop(columns=[c for c in C if c.startswith("r_")]).to_csv(OUT / "candidates.csv", index=False)
print("saved:", ", ".join(sorted(p.name for p in OUT.glob("*.png"))))