from pathlib import Path import argparse from datetime import datetime, timezone import hashlib import json from concurrent.futures import ThreadPoolExecutor import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pandas as pd from PIL import Image, ImageOps import requests HERE = Path(__file__).resolve().parent YEARS = (2019, 2023, 2024, 2025, 2026) FHWA = "https://www.fhwa.dot.gov/bridge/nbi/no10/" SOURCES = {f"bridge-{year}.html": f"{FHWA}condition{year % 100:02d}.cfm" for year in YEARS} SOURCES["bridge-posting-totals-2026.html"] = FHWA + "posting26e.cfm" PHOTO = "https://npgallery.nps.gov/AssetDetail/757ca940-cc97-4b58-95f7-18daabae3831" IMAGE = "https://npgallery.nps.gov/GetAsset/757ca940-cc97-4b58-95f7-18daabae3831/original.jpg" METRICS = ["count", "good_count", "fair_count", "poor_count", "area", "good_area", "fair_area", "poor_area"] EXCLUDE = {"GUAM", "PUERTO RICO", "U.S. VIRGIN ISLANDS", "TOTALS"} SELECTED = ["IOWA", "WEST VIRGINIA", "SOUTH DAKOTA", "PENNSYLVANIA", "NEW YORK", "CALIFORNIA", "MASSACHUSETTS", "NEW JERSEY", "RHODE ISLAND", "TEXAS"] STATE_SHORT = {"IOWA": "IA", "WEST VIRGINIA": "WV", "SOUTH DAKOTA": "SD", "PENNSYLVANIA": "PA", "NEW YORK": "NY", "CALIFORNIA": "CA", "MASSACHUSETTS": "MA", "NEW JERSEY": "NJ", "RHODE ISLAND": "RI", "TEXAS": "TX"} BACK = "#f3ede2" INK = "#2b2421" BLUE = "#185879" RUST = "#ad4b28" GOLD = "#ac7a23" GREY = "#737779" def download_file(item, cache): name, url = item path = cache / name if not path.exists(): response = requests.get(url, headers={"User-Agent": "RouteMeasure data verification/1.0"}, timeout=35) response.raise_for_status() path.write_bytes(response.content) return path def highway_tables(path): frames = [] for table in pd.read_html(path): assert table.shape == (55, 9), (path, table.shape) table.columns = ["state", *METRICS] table["state"] = table["state"].str.rstrip("*") table = table.loc[~table.state.isin(EXCLUDE)].set_index("state") if path.name == "bridge-2024.html" and table.at["DELAWARE", "poor_count"] == "-": # The NHS condition subtotal and area subtotal both exactly exhaust the Delaware total. for total, good, fair, poor in (("count", "good_count", "fair_count", "poor_count"), ("area", "good_area", "fair_area", "poor_area")): assert int(table.at["DELAWARE", total]) == int(table.at["DELAWARE", good]) + int(table.at["DELAWARE", fair]) table.at["DELAWARE", poor] = "0" table[METRICS] = table[METRICS].apply(pd.to_numeric) assert len(table) == 51 and table.index.is_unique assert (table[["good_count", "fair_count", "poor_count"]].sum(axis=1) == table["count"]).all() frames.append(table) assert len(frames) == 2 and frames[0].index.equals(frames[1].index) return frames def add_measures(frame): frame = frame.copy() frame["poor_count_share"] = 100 * frame.poor_count / frame["count"] frame["poor_area_share"] = 100 * frame.poor_area / frame.area frame["area_per_bridge"] = frame.area / frame["count"] frame["area_per_poor_bridge"] = frame.poor_area / frame.poor_count return frame def extract(path, year): all_bridges, nhs = highway_tables(path) outside_nhs = all_bridges - nhs assert outside_nhs.ge(0).all().all() return { system: add_measures(table).assign(year=year, system=system).reset_index() for system, table in [("All inventory", all_bridges), ("NHS", nhs), ("Outside NHS", outside_nhs)] } def national_posting(path): table = next(t for t in pd.read_html(path) if len(t) == 17 and int(t.iloc[-1, 1]) == 624939) table.columns = ["status", *METRICS] return table.set_index("status").drop("TOTALS").apply(pd.to_numeric) def setup_plot(title, subtitle): fig, ax = plt.subplots(figsize=(11, 6.4), dpi=140) fig.patch.set_facecolor(BACK) ax.set_facecolor(BACK) ax.spines[["top", "right", "left"]].set_visible(False) ax.spines["bottom"].set_color("#bfb3a6") ax.tick_params(axis="both", labelsize=11, length=0, pad=7, labelcolor=INK) ax.grid(axis="y", alpha=.22, linewidth=.7) ax.set_axisbelow(True) fig.text(.12, .94, title, color=INK, fontsize=23, fontweight="bold", va="top") fig.text(.12, .865, subtitle, color=INK, fontsize=11, va="top") fig.text(.12, .055, "ROUTEMEASURE / FHWA NATIONAL BRIDGE INVENTORY", color=GREY, fontsize=8) fig.subplots_adjust(left=.16, right=.94, bottom=.18, top=.78) return fig, ax def write_charts(data, posting): (HERE / "charts").mkdir(exist_ok=True) plan = [] def asset(name, title, question, period, unit, takeaway, frame, subtitle, source=FHWA + "condition26.cfm", population="50 states and District of Columbia"): file = f"charts/chart-{len(plan) + 1:02d}-{name}" frame.to_csv(HERE / (file + ".csv"), index=False, float_format="%.8f") plan.append({"asset": file + ".png", "title": title, "question": question, "period": period, "unit": unit, "takeaway": takeaway, "source": source, "population": population, "data": file + ".csv"}) fig, ax = setup_plot(title, subtitle) return file, fig, ax def finish(file, fig): fig.savefig(HERE / (file + ".png"), facecolor=BACK) plt.close(fig) now = data.loc[data.year.eq(2026)] summed = now.groupby("system", sort=False)[METRICS].sum() summed = add_measures(summed) rate = summed[["poor_count_share", "poor_area_share"]].reset_index() file, fig, ax = asset("two-weights", "Two ways to count poor condition", "How do poor shares change when the same inventory is weighted by size?", "2026", "Percent of the corresponding inventory", "Weighting changes both the level and the size of the NHS gap.", rate, "Count gives each bridge one vote. Deck area gives more weight to larger structures.") y = np.arange(len(rate)) ax.hlines(y, rate.poor_area_share, rate.poor_count_share, color="#b3ab9e", linewidth=3) ax.scatter(rate.poor_count_share, y, color=RUST, s=80, label="By bridge count", zorder=3) ax.scatter(rate.poor_area_share, y, color=BLUE, s=80, label="By deck area", zorder=3) ax.set_yticks(y, rate.system) ax.invert_yaxis() ax.set_xlim(0, 9) ax.set_xlabel("Poor share (%)") ax.legend(frameon=False, loc="upper right") finish(file, fig) all_states = now.loc[now.system.eq("All inventory")].copy() x = "poor_count_share" y = "poor_area_share" scatter = all_states[["state", x, y]] file, fig, ax = asset("state-scatter", "Where the two state measures diverge", "In which states is the share by area greater or smaller than the share by count?", "2026", "Percent of bridges and percent of deck area", "Iowa and Massachusetts sit on opposite sides of the matching line.", scatter, "Each mark is a jurisdiction. Equal shares fall on the dashed line.") ax.plot([0, 20], [0, 20], color=GREY, linestyle=":", linewidth=1.5) ax.scatter(scatter[x], scatter[y], color=BLUE, s=25, alpha=.75) for row in scatter.loc[scatter.state.isin(["IOWA", "MASSACHUSETTS", "CALIFORNIA", "NEW YORK", "WEST VIRGINIA"])].itertuples(): ax.annotate(STATE_SHORT[row.state], (row.poor_count_share, row.poor_area_share), xytext=({"MASSACHUSETTS": (-17, 0), "NEW YORK": (4, 7)}.get(row.state, (4, 4))), textcoords="offset points", color=INK, fontsize=10) ax.set(xlim=(0, 20), ylim=(0, 20), xlabel="Poor share by bridge count (%)", ylabel="Poor share by deck area (%)") finish(file, fig) sz = summed[["area_per_bridge", "area_per_poor_bridge"]].loc[["NHS", "Outside NHS"]].reset_index() file, fig, ax = asset("size", "A bridge on the NHS is larger on average", "How much deck area does an average bridge contribute on and off the NHS, including the poor subset?", "2026", "Square feet per structure", "The average poor NHS structure is several times the size of a poor off-system one.", sz, "Average area equals total area divided by the corresponding count.") pos = np.arange(len(sz)) ax.bar(pos - .17, sz.area_per_bridge, .32, color=BLUE, label="All conditions") ax.bar(pos + .17, sz.area_per_poor_bridge, .32, color=RUST, label="Poor condition") ax.set_xticks(pos, sz.system) ax.set_ylabel("Square feet per bridge") ax.legend(frameon=False) finish(file, fig) condition = pd.DataFrame([ {"system": system, "condition": status.title(), "share_of_area": 100 * row[f"{status}_area"]/row.area} for system, row in summed.iterrows() for status in ("good", "fair", "poor") ]) file, fig, ax = asset("composition", "Fair condition covers most bridge area", "How is bridge surface distributed among good, fair and poor classes?", "2026", "Percent of bridge deck area", "Fair is the largest category on both road systems.", condition, "Share of deck area by condition, using each road system’s own denominator.") matrix = condition.pivot(index="system", columns="condition", values="share_of_area").loc[summed.index] bottom = np.zeros(len(matrix)) for label, color in [("Good", BLUE), ("Fair", GOLD), ("Poor", RUST)]: ax.bar(matrix.index, matrix[label], .55, bottom=bottom, color=color, label=label) bottom += matrix[label].to_numpy() ax.set_ylabel("Share of deck area (%)") ax.set_ylim(0, 100) ax.legend(frameon=False, ncol=3, loc="upper center", bbox_to_anchor=(.5, 1.09)) finish(file, fig) select = now.loc[now.state.isin(SELECTED) & ~now.system.eq("All inventory")] per_system = select.pivot(index="state", columns="system", values="poor_area_share").loc[SELECTED] per_system["gap_nhs_minus_off"] = per_system["NHS"] - per_system["Outside NHS"] per_system = per_system.sort_values("gap_nhs_minus_off").reset_index() file, fig, ax = asset("network-gaps", "The highway-system gap can flip", "For illustrative states, is poor area more prevalent on the NHS or off it?", "2026", "Percentage-point gap, NHS minus outside NHS", "The direction of the national difference does not describe each state.", per_system, "Negative = higher outside NHS. Positive = higher on NHS.") ax.barh(per_system.state.str.title(), per_system.gap_nhs_minus_off, color=np.where(per_system.gap_nhs_minus_off.lt(0), BLUE, RUST)) ax.axvline(0, color=INK, lw=.8) ax.set_xlabel("Poor area share difference (percentage points)") finish(file, fig) flow = all_states[["state", "poor_area", "poor_count"]].sort_values("poor_area", ascending=False).reset_index(drop=True) flow["jurisdiction_count"] = np.arange(1, len(flow) + 1) flow["cumulative_poor_area_share"] = 100 * flow.poor_area.cumsum() / flow.poor_area.sum() flow["cumulative_poor_count_share"] = 100 * flow.poor_count.cumsum() / flow.poor_count.sum() file, fig, ax = asset("concentration", "Poor area is geographically concentrated", "How much of the nation’s poor area and poor count sits in the same highest-area states?", "2026", "Cumulative percent of national poor inventory", "Sorting by poor area accumulates area faster than bridge count.", flow, "Jurisdictions are ordered by poor deck area, from the most to the least.") ax.plot(flow.jurisdiction_count, flow.cumulative_poor_area_share, color=BLUE, linewidth=2.5, label="Poor deck area") ax.plot(flow.jurisdiction_count, flow.cumulative_poor_count_share, color=RUST, linewidth=2.5, label="Poor bridge count") ax.set(xlabel="Number of jurisdictions included", ylabel="Share of poor U.S. inventory (%)", ylim=(0, 105)) ax.legend(frameon=False) finish(file, fig) history = data.loc[data.year.lt(2026)].groupby(["year", "system"], sort=False)[METRICS].sum() history = add_measures(history).reset_index() file, fig, ax = asset("history-area", "A quieter change before the data transition", "How did the poor area shares change in the selected pre-transition inventory years?", "2019, 2023, 2024 and 2025", "Percent of bridge deck area", "The two parts of the system had different levels before the 2026 format change.", history[["year", "system", "poor_area_share"]], "Four selected pre-transition snapshots. Lines connect reported observations.", source="https://www.fhwa.dot.gov/bridge/nbi/condition.cfm") for system, color in [("All inventory", GREY), ("NHS", BLUE), ("Outside NHS", RUST)]: series = history.loc[history.system.eq(system)] ax.plot(series.year, series.poor_area_share, marker="o", color=color, linewidth=2, label=system) ax.set(ylabel="Poor area share (%)", ylim=(0, 8), xticks=(2019, 2023, 2024, 2025)) ax.legend(frameon=False) finish(file, fig) old = data.loc[data.year.eq(2025) & data.system.eq("All inventory")].set_index("state") new = all_states.set_index("state") delta = (new.poor_count - old.poor_count).sort_values() extremes = pd.concat([delta.head(5), delta.tail(5)]).rename("change_in_poor_count").reset_index() file, fig, ax = asset("change-counts", "State counts moved in both directions", "Which states had the largest decreases and increases in poor bridge counts between releases?", "2025 to 2026", "Change in number of inventory records", "Large changes in some states offset one another across the inventory.", extremes, "Five largest decreases and increases in poor counts. This is an inventory change, not a bridge-by-bridge repair log.", source="https://www.fhwa.dot.gov/bridge/nbi/condition.cfm") ax.barh(extremes.state.str.title(), extremes.change_in_poor_count, color=np.where(extremes.change_in_poor_count.lt(0), BLUE, RUST)) ax.axvline(0, color=INK, lw=.8) ax.set_xlabel("Change in number of poor bridges") finish(file, fig) grouped_posting = pd.DataFrame([ {"status": label, **posting.iloc[positions][METRICS].sum().to_dict()} for label, positions in [("Open, no restriction", [0, 1, 2]), ("Posted for load", [8, 9, 10]), ("Closed", [7]), ("Other status", [3, 4, 5, 6, 11, 12, 13, 14, 15])] ]) assert grouped_posting["count"].sum() == 624939 assert grouped_posting.poor_count.sum() == 41148 for status in ("good", "fair", "poor"): grouped_posting[status + "_share"] = (100 * grouped_posting[status + "_count"] / grouped_posting[status + "_count"].sum()) file, fig, ax = asset("posting", "Poor condition does not specify posting", "How are the separately reported posting statuses distributed within each condition?", "2026", "Percent of structure count within condition", "Poor bridges appear in several operational status groups.", grouped_posting, "National posting table includes territories. Denominators are condition-specific.", source=SOURCES["bridge-posting-totals-2026.html"], population="FHWA national posting totals, including reported territories") pos = np.arange(len(grouped_posting)) for offset, status, color in [(-.23, "good", BLUE), (0, "fair", GOLD), (.23, "poor", RUST)]: ax.bar(pos + offset, grouped_posting[status + "_share"], .22, color=color, label=status.title()) ax.set_xticks(pos, grouped_posting.status, fontsize=9) ax.set_ylabel("Share within condition (%)") ax.legend(frameon=False) finish(file, fig) (HERE / "CHART-PLAN.json").write_text(json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") return summed, scatter, sz, condition, per_system, flow, history, extremes, grouped_posting def prepare_photo(path): meta = {"title": "New River Gorge Bridge from Long Point Trail", "alt": "A steel arch highway bridge spans a forested gorge in West Virginia.", "caption": ("A representative photograph of the New River Gorge Bridge from Long Point Trail " "in West Virginia. Statewide inventory figures do not describe the bridge in the photograph."), "credit": "Dave Bieri / National Park Service", "source_url": PHOTO, "license": "Public domain (U.S. government)", "license_url": PHOTO, "original_url": IMAGE, "original_sha256": hashlib.sha256(path.read_bytes()).hexdigest()} with Image.open(path) as image: assert image.width >= 1600 and image.height >= 900 preview = ImageOps.fit(ImageOps.exif_transpose(image).convert("RGB"), (1600, 900), method=Image.Resampling.LANCZOS, centering=(.5, .10)) preview.save(HERE / "hero.webp", quality=86, method=6) meta["processing"] = (f"Cropped the {image.width} × {image.height} original to 16:9, " "resized without upscaling to 1600 × 900, and encoded as WebP.") (HERE / "HERO.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--cache", type=Path, default=Path.cwd() / ".bridge-inputs", help="Directory for original FHWA HTML snapshots and NPS photograph") args = parser.parse_args() args.cache.mkdir(parents=True, exist_ok=True) sources = SOURCES | {"bridge-hero.jpg": IMAGE} with ThreadPoolExecutor(max_workers=4) as pool: files = dict(zip(sources, pool.map(lambda item: download_file(item, args.cache), sources.items()))) data = pd.concat([frame for year in YEARS for frame in extract(files[f"bridge-{year}.html"], year).values()], ignore_index=True) (HERE / "source-manifest.json").write_text(json.dumps({ "verified_utc": datetime.now(timezone.utc).isoformat(), "sources": [{"url": url, "bytes": files[name].stat().st_size, "sha256": hashlib.sha256(files[name].read_bytes()).hexdigest()} for name, url in sources.items()] }, indent=2) + "\n", encoding="utf-8") posting = national_posting(files["bridge-posting-totals-2026.html"]) data.to_csv(HERE / "bridge-summary.csv", index=False, float_format="%.8f") posting.to_csv(HERE / "posting-summary.csv") summaries = write_charts(data, posting) prepare_photo(files["bridge-hero.jpg"]) for frame in summaries: print(frame.head(15).to_string(index=True)) if __name__ == "__main__": main()