"""Rebuild RouteMeasure's pedestrian-lighting evidence, CSVs and charts.""" import hashlib import json import sys import zipfile from pathlib import Path import pandas as pd ARTICLE = Path(__file__).resolve().parent EDITORIAL = ARTICLE.parents[2] ROOT = EDITORIAL.parent sys.path.insert(0, str(EDITORIAL / "launch-2026-12-03")) from charting import save_chart YEARS = list(range(2019, 2025)) SOURCE = "https://www.nhtsa.gov/crash-data-systems/fatality-analysis-reporting-system" FACT_SHEET = "https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813818" PALETTE = ["#fff8f2", "#30211b", "#844421", "#225568", "#76639b", "#477052", "#b27632"] DAY = "Daylight" UNLIT = "Dark, not lighted" LIT = "Dark, lighted" DARK_UNKNOWN = "Dark, lighting unknown" TWILIGHT = "Dawn or dusk" UNCLASSIFIED = "Other or unreported" LIGHT = {1: DAY, 2: UNLIT, 3: LIT, 4: TWILIGHT, 5: TWILIGHT, 6: DARK_UNKNOWN} ORDER = [DAY, UNLIT, LIT, DARK_UNKNOWN, TWILIGHT, UNCLASSIFIED] DARK = [UNLIT, LIT, DARK_UNKNOWN] STATE_SCOPE = {1,2,4,5,6,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31, 32,33,34,35,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,53,54,55,56} AGE_LABELS = ["Under 18", "18–34", "35–54", "55–64", "65+"] HOUR_LABELS = ["12–3 am", "3–6 am", "6–9 am", "9 am–noon", "Noon–3 pm", "3–6 pm", "6–9 pm", "9 pm–midnight"] SEASON = {m: label for label, months in (("Winter", [12,1,2]),("Spring", [3,4,5]),("Summer", [6,7,8]),("Fall", [9,10,11])) for m in months} SEASONS = ["Winter", "Spring", "Summer", "Fall"] ROAD = {1: "Interstate",2: "Other freeway",3: "Principal arterial",4:"Minor arterial", 5:"Major collector",6:"Minor collector",7:"Local"} def from_archive(archive, name, usecols): member = next(path for path in archive.namelist() if path.rsplit("/", 1)[-1].casefold() == name) with archive.open(member) as stream: return pd.read_csv(stream, encoding="utf-8-sig", encoding_errors="replace", usecols=usecols) def load(): collection = json.loads((ROOT / "research/collection_batch_2026-11-29.json").read_text(encoding="utf-8")) observed = {record["id"]: record for record in collection["items"]} pedestrians, totals, source_files = [], [], [] for year in YEARS: record = observed[f"nhtsa_fars_{year}"] archive_path = ROOT / record["local_path"] with archive_path.open("rb") as stream: digest = hashlib.file_digest(stream, "sha256").hexdigest() if record.get("sha256") and digest != record["sha256"]: raise ValueError(f"Archive digest changed for {year}") with zipfile.ZipFile(archive_path) as archive: crashes = from_archive(archive, "accident.csv", [ "STATE", "STATENAME", "ST_CASE", "YEAR", "MONTH", "HOUR", "LGT_COND", "RUR_URB", "FUNC_SYS", "FATALS"]) persons = from_archive(archive, "person.csv", ["STATE", "ST_CASE", "PER_NO", "VEH_NO", "AGE", "INJ_SEV", "PER_TYP"]) crashes = crashes[crashes.STATE.isin(STATE_SCOPE)] persons = persons[persons.STATE.isin(STATE_SCOPE) & (persons.PER_TYP == 5) & (persons.INJ_SEV == 4)] if set(crashes.YEAR) != {year} or persons.duplicated(["STATE", "ST_CASE", "VEH_NO", "PER_NO"]).any(): raise ValueError(f"Unexpected source years or duplicate people for {year}") matched = persons.merge(crashes, on=["STATE", "ST_CASE"], how="left", validate="many_to_one", indicator=True) if not matched._merge.eq("both").all(): raise ValueError(f"Fatal pedestrian records do not all match a crash for {year}") matched["Light"] = matched.LGT_COND.map(LIGHT).fillna(UNCLASSIFIED) matched["Dark"] = matched.Light.isin(DARK) matched["Area"] = matched.RUR_URB.map({1: "Rural", 2: "Urban"}).fillna("Unknown") matched["Age group"] = pd.cut(matched.AGE, [-1,17,34,54,64,125], labels=AGE_LABELS) matched["Hour block"] = pd.cut(matched.HOUR, [-1,2,5,8,11,14,17,20,23], labels=HOUR_LABELS) matched["Season"] = matched.MONTH.map(SEASON) matched["Road class"] = matched.FUNC_SYS.map(ROAD).fillna("Other or unknown") pedestrians.append(matched) totals.append({"Year": year, "All traffic deaths": int(crashes.FATALS.sum()), "Pedestrian deaths": len(matched)}) source_files.append({"year": year, "url": record["source_url"], "sha256": digest}) print(year, len(matched), flush=True) return pd.concat(pedestrians), pd.DataFrame(totals).set_index("Year"), source_files def counts(frame, row, column): return pd.crosstab(frame[row], frame[column]) def as_values(data, order): return {column: data.reindex(order).fillna(0)[column].tolist() for column in data.columns} def build(): people, annual, source_files = load() current = people[people.YEAR == 2024] start = people[people.YEAR == 2019] lights = counts(people, "YEAR", "Light").reindex(columns=ORDER, fill_value=0) annual["Dark"] = lights[DARK].sum(axis=1) annual["Pedestrian share (%)"] = 100 * annual["Pedestrian deaths"] / annual["All traffic deaths"] annual["Dark share (%)"] = 100 * annual["Dark"] / annual["Pedestrian deaths"] if not annual["Pedestrian deaths"].eq(lights.sum(axis=1)).all(): raise ValueError("Lighting counts do not reconcile to annual pedestrian totals") place = counts(current, "Area", "Light").reindex(columns=ORDER, fill_value=0) ages = counts(current, "Age group", "Light").reindex(columns=ORDER, fill_value=0) hours = counts(current, "Hour block", "Light").reindex(columns=ORDER, fill_value=0) seasons = counts(people[people.YEAR.isin((2019, 2024))], "Season", "YEAR").reindex(SEASONS) season_dark = counts(people[people.YEAR.isin((2019, 2024)) & people.Dark], "Season", "YEAR").reindex(SEASONS) by_state = counts(people[people.YEAR.isin((2019, 2024))], "STATENAME", "YEAR") by_state_dark = counts(people[people.YEAR.isin((2019, 2024)) & people.Dark], "STATENAME", "YEAR").reindex(by_state.index,fill_value=0) comparison = by_state.rename(columns={2019:"2019 Total",2024:"2024 Total"}).join( by_state_dark.rename(columns={2019:"2019 Dark",2024:"2024 Dark"})) comparison["Total change"] = comparison["2024 Total"] - comparison["2019 Total"] comparison["Dark change"] = comparison["2024 Dark"] - comparison["2019 Dark"] comparison["Other change"] = comparison["Total change"] - comparison["Dark change"] road = counts(current, "Road class", "Light").reindex(columns=ORDER, fill_value=0) road["Total"] = road.sum(axis=1) road["Dark"] = road[DARK].sum(axis=1) plotted = ARTICLE / "charts" plotted.mkdir(exist_ok=True) evidence = ARTICLE / "data" evidence.mkdir(exist_ok=True) results = { "annual": annual, "annual-light": lights, "area-light": place, "age-light": ages, "hour-light": hours, "by-state": comparison, "seasons": seasons, "season-dark": season_dark, "road-light": road, } for name, values in results.items(): values.to_csv(evidence / f"{name}.csv") (evidence / "sources.json").write_text(json.dumps({"definition": SOURCE,"fact_sheet": FACT_SHEET, "archives": source_files,"method": { "unmatched_fatal_pedestrian_rows":0, "unknown_age_2024":int(current["Age group"].isna().sum()), "unknown_hour_2024":int(current["Hour block"].isna().sum()), "crash_join":["STATE","ST_CASE"], "light_condition_codes":dict(LIGHT), "pedestrian_person_type":5,"fatal_injury_code":4, "geography":"50 states and District of Columbia"}}, indent=2, ensure_ascii=False)+"\n",encoding="utf-8") plan = [] def chart(stem, title, unit, labels, series, question, takeaway, period, population, kind="bar"): save_chart(plotted, stem, title=title, unit=unit, labels=labels, series=series, source="NHTSA Fatality Analysis Reporting System", palette=PALETTE, kind=kind) plan.append({"asset":f"charts/{stem}.png","question":question,"source":SOURCE, "population":population,"period":period,"unit":unit,"takeaway":takeaway, "title":title,"data":f"charts/{stem}.csv"}) pop = "Fatal pedestrian person records in the 50 states and District of Columbia" chart("chart-01-annual-deaths", "Deaths after dark and all pedestrian deaths", "People killed", YEARS, {"All pedestrian deaths":annual["Pedestrian deaths"],"In dark conditions":annual["Dark"]}, "How did pedestrian deaths and their dark-condition subset change?", "The dark-condition subset accounts for most deaths throughout this period.", "2019–2024", pop, "line") difference = lights.loc[2024] - lights.loc[2019] chart("chart-02-light-change", "Lighting categories contributed unevenly", "Change in pedestrian deaths", ORDER, {"2024 minus 2019":difference.reindex(ORDER)}, "Which reported light conditions accounted for the net change?", "The two categories with known dark lighting account for most of the increase.", "2019 to 2024", pop) chart("chart-03-dark-share", "Share in dark conditions remained elevated", "Percent of pedestrian deaths", YEARS, {"Dark-condition share":annual["Dark share (%)"]}, "Did the dark share stay high as the total declined?", "Uses the share of fatal pedestrian records, rather than a walking exposure rate.", "2019–2024", pop, "line") place_fractions = place[[UNLIT,LIT]].div(place.sum(axis=1),axis=0).mul(100).reindex(["Urban","Rural"]) chart("chart-04-urban-rural-light", "Dark conditions differed by area type", "Percent of pedestrian deaths within each area", ["Urban","Rural"], as_values(place_fractions, ["Urban","Rural"]), "How did lighted and unlighted dark conditions compare between rural and urban crashes?", "Breaks the dark subset into reported roadway lighting conditions.", "2024", pop) hour_plotted = pd.DataFrame({"In dark conditions":hours[DARK].sum(axis=1),"Daylight":hours[DAY]}) chart("chart-05-clock-hours", "Evening and daylight carry different totals", "People killed", HOUR_LABELS, as_values(hour_plotted,HOUR_LABELS), "In which local clock-hour blocks did reported dark or daylight deaths concentrate?", "Unknown crash hours and other light categories are left out of this figure.", "2024", pop) age_ranges = ages[DARK].sum(axis=1).div(ages.sum(axis=1)).mul(100) chart("chart-06-age-composition", "Dark-condition share varies by age", "Percent of pedestrian deaths within each age group", AGE_LABELS, {"Dark-condition share":age_ranges.reindex(AGE_LABELS)}, "Did the share of deaths in darkness differ among age groups?", "Age groups describe fatal records with known age, rather than a risk per person of that age.", "2024", pop) states = list(comparison.nlargest(7,"2024 Total").index) chart("chart-07-state-change", "Changes differ among the largest state totals", "Change in pedestrian deaths", states, {"Dark conditions":comparison.loc[states,"Dark change"],"Other conditions":comparison.loc[states,"Other change"]}, "How much of the change came from dark or other light conditions in the seven largest 2024 state totals?", "Orders states by 2024 pedestrian deaths rather than by change or population.", "2019 to 2024", pop) season_plotted = pd.DataFrame({"2019": 100*season_dark[2019]/seasons[2019], "2024": 100*season_dark[2024]/seasons[2024]}) chart("chart-08-seasonal-comparison", "Season changes the dark-condition share", "Percent of pedestrian deaths within each season", SEASONS, as_values(season_plotted,SEASONS), "Were dark-condition shares similar across matched seasons?", "Winter pools December, January and February within each named calendar year.", "2019 and 2024", pop) roads = list(road.nlargest(5,"Total").index) chart("chart-09-road-class", "Principal arterials account for the largest count", "People killed", roads, {"On dark roadways":road.loc[roads,"Dark"],"Other light conditions":(road.Total-road.Dark).loc[roads]}, "How large were the dark and other splits across the five road classes with most deaths?", "These are fatality counts without a pedestrian or traffic exposure denominator.","2024",pop) (ARTICLE / "CHART-PLAN.json").write_text(json.dumps(plan,ensure_ascii=False,indent=2)+"\n",encoding="utf-8") if __name__ == "__main__": build()